# A. Minimum Number of Operations to Convert Time (opens new window)
Greedy Get time difference.
DETAILS
def convertTime(self, A: str, B: str) -> int:
dif = (int(B[:2]) - int(A[:2])) * 60 + (int(B[3:]) - int(A[3:]))
ans, dif = dif // 60, dif % 60
ans, dif = ans + dif // 15, dif % 15
ans, dif = ans + dif // 5, dif % 5
return ans + dif
# B. Find Players With Zero or One Losses (opens new window)
DETAILS
def findWinners(self, A: List[List[int]]) -> List[List[int]]:
ppl = [0] * (10**5 + 1)
lose = [0] * (10**5 + 1)
for w, l in A:
ppl[w] += 1
ppl[l] += 1
lose[l] += 1
ans = [[], []]
for i in range(10**5 + 1):
if ppl[i] > 0 and lose[i] == 0:
ans[0].append(i)
if ppl[i] > 0 and lose[i] == 1:
ans[1].append(i)
return ans
# C. Maximum Candies Allocated to K Children (opens new window)
Binary search: can we allocate k
candies to each child?
DETAILS
def maximumCandies(self, A: List[int], ppl: int) -> int:
l, r = 1, max(A)
if sum(A) < ppl: return 0
while l < r:
m = (r + l + 1) // 2
cur = 0
for a in A:
cur += a // m
if cur >= ppl:
l = m
else:
r = m - 1
return l
# D. Encrypt and Decrypt Strings (opens new window)
HashMap
DETAILS
class Encrypter:
def __init__(self, K: List[str], V: List[str], D: List[str]):
self.dict = set(D)
self.trans = collections.defaultdict(str)
self.back = collections.defaultdict(list)
for pre, suf in zip(K, V):
self.trans[pre] = suf
self.back[suf].append(pre)
def encrypt(self, word1: str) -> str:
ans = ""
for ch in word1:
ans += self.trans[ch]
return ans
def decrypt(self, word2: str) -> int:
ans = 0
for word in self.dict:
cur = ""
valid = True
for ch in word:
if ch in self.trans:
cur += self.trans[ch]
else:
valid = False
continue
if valid:
ans += int(cur == word2)
return ans