The number of participants in biweekly contests has almost caught up with weekly contests.
1925. Count Square Sum Triples
A warm-up problem. Brute-force enumerate all combinations.
1 2 3 4 5 6 7 8 9 10
classSolution: defcountTriples(self, n: int) -> int: ans = 0 for c inrange(1, n+1): for b inrange(1, c+1): for a inrange(1, b+1): if a * a + b * b == c * c: if a == b: ans += 1 else: ans += 2 return ans
classSolution: defnearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: visited = set() q = deque() start = (entrance[0], entrance[1]) visited.add(start) q.append(start) step = 0 directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] rows = len(maze) cols = len(maze[0]) defexitCell(cell): return (cell[0] == 0or cell[0] == rows - 1or cell[1] == 0or cell[1] == cols - 1) and maze[cell[0]][cell[1]] == '.'and cell != start while q: s = len(q) for _ inrange(s): current = q.popleft() if exitCell(current): return step for di, dj in directions: ni = di + current[0] nj = dj + current[1] if ni >= 0and ni < rows and nj >= 0and nj < cols and maze[ni][nj] == '.'and (ni, nj) notin visited: visited.add((ni, nj)) q.append((ni,nj)) step += 1 return -1
Time complexity: O(m * n), Space complexity: O(m * n).
1927. Sum Game
Greedy.
Try to pick from the side with fewer question marks first until that side is exhausted. Alice tries to make the difference larger, and Bob tries to make the difference smaller.
The idea was fine, but the code I wrote in the end was ugly and long. I only got it accepted 13 minutes before the contest ended.
classSolution: defsumGame(self, num: str) -> bool: n = len(num) leftSum = 0 rightSum = 0 left = 0 right = 0 for i inrange(n): if num[i] == '?': if i >= n // 2: right += 1 else: left += 1 else: if i >= n // 2: rightSum += ord(num[i]) - ord('0') else: leftSum += ord(num[i]) - ord('0') total = right + left # print ('total: ', total) if total % 2 == 1: returnTrue alice = True for _ inrange(total): if alice: if left == 0or (right != 0and left > right): # pick right if leftSum <= rightSum or rightSum + 9 > leftSum: rightSum += 9 else: rightSum += 0 right -= 1 elif right == 0or left < right: # pick left if leftSum >= rightSum or leftSum + 9 > rightSum: leftSum += 9 else: leftSum += 0 left -= 1 else: if leftSum == rightSum: returnFalse elif leftSum > rightSum: leftSum += 9 left -= 1 else: rightSum += 9 right -= 1 else: if left == 0or (right != 0and left > right): # pick right if leftSum > rightSum: rightSum += 9if (leftSum - rightSum > 9) else leftSum - rightSum else: rightSum += 0 right -= 1 elif right == 0or left < right: # pick left if leftSum < rightSum: leftSum += 9if (rightSum - leftSum > 9) else rightSum - leftSum else: leftSum += 0 left -= 1 # print (left, leftSum, rightSum, right) alice = not alice return leftSum != rightSum
Time complexity: O(num.length), Space complexity: O(num.length).
1928. Minimum Cost to Reach Destination in Time
This is also a classic problem: minimize the cost under a time constraint.