← Expedia Interview InsightsSoftware Engineer
My first instinct was to just sort and interleave, which works but I fumbled explaining why it works.
Use a max-heap to greedily place the most frequent remaining element that differs from the last placed element. This ensures the most frequent elements are placed early and avoids adjacent duplicates. The guaranteed existence of a valid arrangement means the greedy choice will always succeed.
Pro tip: After presenting the heap solution, mention that a simpler O(n) approach exists using the majority element (if any) and interleaving, but the heap method is more general and easier to reason about under pressure.
Restate the problem: rearrange array so no two adjacent elements are equal, and a valid arrangement is guaranteed. Confirm input size and constraints (e.g., can elements be negative? duplicates?).
Use a max-heap (priority queue) keyed by frequency to always access the most frequent remaining element. Alternatively, consider sorting and interleaving, but heap is more straightforward.
While heap has elements: pop the most frequent element. If it equals the last placed element, pop the next most frequent, place it, then push back the first if its count > 0. Otherwise, place the popped element and push back if count > 0.
If heap becomes empty but last element still has count > 0, it means no valid arrangement (but problem guarantees one). Also handle single-element array and all elements same (only possible if length 1).
Time: O(n log k) where k is number of distinct elements, typically O(n log n). Space: O(n) for the heap and result array.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.