Bird
Raised Fist0

Consider the following buggy code for reorganizing a string. Which line contains the subtle bug that can cause the function to return an invalid string with adjacent identical characters?

medium🐞 Bug Identification Q14 of Q15
Greedy Algorithms - Reorganize String (No Two Adjacent Same)
Consider the following buggy code for reorganizing a string. Which line contains the subtle bug that can cause the function to return an invalid string with adjacent identical characters?
import heapq
from collections import Counter

def reorganizeString(s: str) -> str:
    freq = Counter(s)
    max_heap = [(-count, ch) for ch, count in freq.items()]
    heapq.heapify(max_heap)
    prev_count, prev_char = 0, ''
    result = []

    while max_heap:
        count, ch = heapq.heappop(max_heap)
        result.append(ch)
        # Bug: missing check for impossible case
        if prev_count < 0:
            heapq.heappush(max_heap, (prev_count, prev_char))
        prev_count, prev_char = count + 1, ch

    res_str = ''.join(result)
    if len(res_str) != len(s):
        return ""
    return res_str
AMissing check before the while loop to verify if max frequency exceeds (n+1)/2
BLine where prev_count and prev_char are updated after appending
CLine where the previous character is pushed back into the heap
DLine where max_heap is initialized with negative counts
Step-by-Step Solution
Solution:
  1. Step 1: Identify missing validation

    The code lacks a check before the loop to verify if the most frequent character count exceeds (n+1)/2, which makes rearrangement impossible.
  2. Step 2: Understand consequences

    Without this check, the algorithm may produce invalid strings with adjacent duplicates or fail silently.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Adding this check prevents impossible cases early [OK]
Quick Trick: Check max frequency before processing [OK]
Common Mistakes:
MISTAKES
  • Forgetting impossible case check
  • Misplacing heap pushback logic
  • Incorrect prev_count update
Trap Explanation:
PITFALL
  • Candidates often overlook the feasibility check, assuming heap logic suffices for all inputs.
Interviewer Note:
CONTEXT
  • Tests if candidate knows necessary preconditions for greedy heap approach correctness.
Master "Reorganize String (No Two Adjacent Same)" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes