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?
  1. A. ababac '' vlvov
  2. B. ababac '' vvlov
  3. C. ababac 'abaa' vlvov
  4. 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

Exams that ask this topic