Collapse Repeat Visits and Order the Result
Heaps, Sorting & SearchAuto-graded · 25 test casesLast updated
Tests array manipulation, hash-based deduplication, and implementing an O(n log n) sort from scratch without relying on built-in sort utilities.
Problem
You are given an integer array visits of up to 75 elements. The array is unsorted and may contain repeated values.
Your task is to process the array in two steps:
- Collapse repeats. For each distinct value, preserve its first occurrence exactly as-is. Every subsequent occurrence of that same value must be replaced with
0. - Order the result. Sort the transformed array in non-decreasing order.
Return the final sorted array.
Rules
- Do not use any built-in or library sorting function (e.g.
sorted(),list.sort(),heapq, etc.). Implement the sort yourself. - Keep time and space complexity in mind when designing your solution.
- The value
0is treated like any other integer during sorting — it is not automatically placed at the front if negative numbers are present. - The input array should not be modified; return a new array.
Constraints
0 <= len(visits) <= 75- Each element is an integer in the range
[-10^4, 10^4] - The array is not sorted and may contain any number of duplicates
- No built-in or third-party sort implementation may be used
Examples
Example 1
Input: collapse_repeats_and_sort([3, 1, 3, 2, 2])
Output: [0, 0, 1, 2, 3]
Example 2
Input: collapse_repeats_and_sort([4, 1, 3, 2])
Output: [1, 2, 3, 4]
Example 3
Input: collapse_repeats_and_sort([5, 5, 5, 5])
Output: [0, 0, 0, 5]
Hints
Hint 1
For the deduplication step, think about what data structure lets you check in O(1) whether you have already encountered a value — and what you append when you have versus when you haven't.
Hint 2
For the sort, consider which O(n log n) algorithm uses O(1) auxiliary space and has no worst-case performance pitfall. It works in two phases: building a particular tree-like structure in place, then repeatedly extracting the maximum.
Hint 3
Watch out for the off-by-one in your sift-down loop: the boundary passed to sift_down must be the current end of the unsorted region, not the total length of the array, or already-sorted elements will get shuffled back in.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has two independent phases.
Phase 1 — Collapsing repeats
Iterate through visits while maintaining a set of values already encountered. For each element:
- If it is already in the set, append
0to the output list. - Otherwise, record it in the set and append it as-is.
A hash set makes each membership check O(1) on average, keeping the whole phase O(n). Using a plain list for "seen" would degrade this to O(n²).
One subtle edge case: if 0 itself appears more than once, the extra copies get replaced with 0, which is a no-op — the result is still correct. If the array contains negative numbers, the zeros introduced here will sort after those negatives, not at the very front.
Phase 2 — Heapsort
The problem bans built-in sorts and asks for efficiency. Among self-implemented comparison sorts:
- Merge sort needs O(n) auxiliary space for the merge step.
- Quicksort degrades to O(n²) on adversarial or already-sorted input.
- Heapsort guarantees O(n log n) in all cases and sorts in place with O(1) auxiliary space.
Heapsort proceeds in two steps:
Build a max-heap. Call sift_down on every internal node from index n//2 - 1 down to 0. This establishes the invariant that result[0] is always the largest element in the unsorted prefix. The total work here is O(n).
Extract repeatedly. Swap the root (the current maximum) with the last element of the unsorted region, then shrink that region by one and call sift_down(0, end) to restore the heap. Each extraction costs O(log n), and there are n − 1 of them, giving O(n log n) total.
sift_down(root, end) is an iterative routine that pushes a misplaced root downward. At each level it picks the larger of the two children; if the root is already at least as large, it stops. The critical detail is passing end (the current boundary of the unsorted region) rather than n — otherwise already-sorted elements at the tail get pulled back into the heap.
Why it is correct
After phase 1, every distinct value appears exactly once in result; all extra copies have become 0. After phase 2, heapsort's loop invariant guarantees that result[end:] always holds the largest n − end elements in sorted order. When end reaches 1, the full array is sorted non-decreasingly.
Complexity
| Phase | Time | Auxiliary space |
|---|---|---|
| Collapse repeats | O(n) average | O(n) for the set and output list |
| Heap construction | O(n) | O(1) |
| Heap extractions | O(n log n) | O(1) |
| Total | O(n log n) | O(n) (from dedup structures) |
The sort itself adds no extra space beyond a few index variables. sift_down is iterative, so there is no hidden recursion-stack cost.
Edge cases
- Empty array: both phases iterate zero times; returns
[]. - Single element: returned unchanged.
- All identical, e.g.
[5, 5, 5]: becomes[5, 0, 0], then sorts to[0, 0, 5]. - No duplicates: phase 1 is a no-op; result is just a sorted copy.
- Negatives present:
[-3, 2, -3]→[-3, 2, 0]→[-3, 0, 2]. Zeros sort by value.
Reference solution
from typing import List
def collapse_repeats_and_sort(visits: List[int]) -> List[int]:
# Step 1: collapse repeats.
# Track which values have already been emitted. The first time a value is
# seen, keep it; every subsequent occurrence becomes 0.
seen = set()
result = []
for value in visits:
if value in seen:
result.append(0)
else:
seen.add(value)
result.append(value)
# Step 2: in-place heapsort — O(n log n) worst-case, O(1) auxiliary space.
n = len(result)
def sift_down(root: int, end: int) -> None:
# Restore the max-heap property within result[0:end], starting at root.
while 2 * root + 1 < end:
child = 2 * root + 1
# Prefer the larger child.
if child + 1 < end and result[child] < result[child + 1]:
child += 1
# Heap property already satisfied; nothing left to do.
if result[root] >= result[child]:
return
result[root], result[child] = result[child], result[root]
root = child
# Build a max-heap by sifting down every internal node, bottom-up.
for start in range(n // 2 - 1, -1, -1):
sift_down(start, n)
# Repeatedly move the current maximum to the end of the unsorted region,
# then shrink that region and re-heapify.
for end in range(n - 1, 0, -1):
result[0], result[end] = result[end], result[0]
sift_down(0, end)
return result