KatInterview

Collapse Repeat Visits and Order the Result

Heaps, Sorting & SearchAuto-graded · 25 test cases
MediumAuto-gradedHeaps, Sorting & Searcharrayssortinghashing

Last 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:

  1. 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.
  2. 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 0 is 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.