Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining letter that differs from the previous one, using a heap and holding back the letter just used.
Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining letter that differs from the previous one, using a heap and holding back the letter just used.
import heapq
from collections import Counter
def reorganize(s):
h = [(-c, ch) for ch, c in Counter(s).items()]; heapq.heapify(h)
out, prev = [], None
while h:
c, ch = heapq.heappop(h); out.append(ch)
if prev: heapq.heappush(h, prev)
prev = (c + 1, ch) if c + 1 < 0 else None
return "".join(out) if not prev else ""
print(reorganize("aaabbc"), repr(reorganize("aaab")), reorganize("vvvlo"))What is printed?- A. ababac '' vlvov
- B. ababac '' vvlov
- C. ababac 'abaa' vlvov
- D. abacab '' vlvov
Correct answer: A. ababac '' vlvov
The letter just placed sits out one turn (prev) and returns to the heap after the next placement; ties in count break alphabetically. "aaabbc" → a b a b a c. "aaab": a b a, then only 'a' remains while prev holds it → impossible (a letter with count > ⌈n/2⌉ always fails). "vvvlo" → v l v o v. O(n log k).
More Coding Interview Problems questions
- Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them. python…
- Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected…
- Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation…
- Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path). python INF = float("inf") def floyd(n…
- Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect…
- Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check…