Got it! Since you’ve already solved 100 LeetCode questions and are preparing for Amazon’s coding OA, let’s focus on more advanced strategies and problem types that are specifically common in Amazon assessments. I’ll also highlight some important patterns, pitfalls, and performance optimization tips for those high-value problems that can often appear in Amazon’s OA.
from heapq import heappush, heappop
def reorganize_string(S):
heap = []
count = Counter(S)
for key, value in count.items():
heappush(heap, (-value, key)) # Max heap by frequency
result = []
while len(heap) > 1:
first, second = heappop(heap), heappop(heap)
result.append(first[1])
result.append(second[1])
if first[0] + 1 < 0:
heappush(heap, (first[0] + 1, first[1]))
if second[0] + 1 < 0:
heappush(heap, (second[0] + 1, second[1]))
if heap:
result.append(heap[0][1])
return "".join(result) if len(result) == len(S) else ""
Pro Tips:
def k_closest(points, K):
heap = []
for (x, y) in points:
dist = -(x*x + y*y) # Use negative for max-heap simulation if len(heap) == K:
heappushpop(heap, (dist, x, y))
else:
heappush(heap, (dist, x, y))
return [(x, y) for (dist, x, y) in heap]
Pro Tips:
def num_islands(grid):
def dfs(i, j):
if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] == '0':
return grid[i][j] = '0' dfs(i+1, j)
dfs(i-1, j)
dfs(i, j+1)
dfs(i, j-1)
count = 0 for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(i, j)
count += 1 return count