# A. First Letter to Appear Twice (opens new window)
Iterate over the string and return the first character that appears twice.
DETAILS
def repeatedCharacter(self, S: str) -> str:
counter = [0] * 26
for ch in S:
counter[ord(ch) - ord('a')] += 1
if counter[ord(ch) - ord('a')] == 2:
return ch
# B. Equal Row and Column Pairs (opens new window)
Collect all rows from A
in counter, then find the number of occurrence of each row of A
in that counter.
DETAILS
def equalPairs(self, A: List[List[int]]) -> int:
C = collections.Counter(tuple(a) for a in A)
return sum(C[tuple(a[::-1])] for a in list(zip(*A[::-1])))
# C. Design a Food Rating System (opens new window)
Use sorted container, or priority queue.
DETAILS
from sortedcontainers import SortedList
class FoodRatings:
def __init__(self, F: List[str], C: List[str], R: List[int]):
self.F, self.pq = {}, defaultdict(SortedList)
for f, c, r in zip(F, C, R):
self.F[f] = (c, r)
self.pq[c].add((-r, f))
def changeRating(self, fd: str, nr: int) -> None:
cu, pr = self.F[fd]
self.F[fd] = (cu, nr)
self.pq[cu].remove((-pr, fd))
self.pq[cu].add((-nr, fd))
def highestRated(self, cu: str) -> str:
return self.pq[cu][0][1]
# D. Number of Excellent Pairs (opens new window)
Please refer to This LC Discussion (opens new window) for my solutions in English.
DETAILS
def countExcellentPairs(self, A: List[int], k: int) -> int:
def cb(n):
ans = 0
while n:
ans += n & 1
n >>= 1
return ans
ans, C = 0, [0] * 31
for a in set(A):
C[cb(a)] += 1
for i in range(1, 31):
for j in range(1, 31):
if i + j >= k:
ans += C[i] * C[j]
return ans