← Questions

Zero out duplicates and sort an array

0
AppleCodingLast asked Feb 2026

A coding interview question asked in Apple's technical phone screen, last asked Feb 2026. It tests arrays, sorting and hash set.

You get an unsorted integer array of around 75 values that may contain duplicates. Keep the first occurrence of each value, replace every later occurrence with 0, then return the array sorted in non-decreasing order. You may not call a built-in sort or a library sorting routine: write the sort yourself.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • zero_dups_and_sort(arr: list[int]) -> list[int]: returns the transformed, sorted array.

Example

[3, 1, 3, 2, 2]               ->  [0, 0, 1, 2, 3]       # [3, 1, 0, 2, 0], then sorted
[4, -2, 7, 4, 4, 9, -2, 0]    ->  [-2, 0, 0, 0, 0, 4, 7, 9]
[5, 0, 0, 1]                  ->  [0, 0, 1, 5]          # a repeated 0 is still a duplicate
[]                            ->  []

Constraints

  • Usually about 75 elements; your solution should still work for 10^5.
  • Values may be negative.
  • No sort(), sorted() or library sort.

Clarifying questions

  • Which copy is kept: the first one?
  • Do negative numbers sort below the zeros that replaced duplicates?
  • May I modify the input, or must I return a new array?
  • Is the value range small enough for a counting approach?

What a strong answer covers

  • One pass with a hash set to zero out repeats, O(n).
  • A hand-written O(n log n) sort (merge sort, or heap sort for O(1) extra space), and why insertion sort is fine at n = 75 but not at 10^5.
  • A counting-based alternative when values are bounded.
  • Tests: no duplicates, all equal, zeros already present, negatives, empty.

Follow-ups

  • Do it in place with O(1) extra space.
  • Keep the last occurrence instead of the first.
  • Remove the duplicates instead of zeroing them.

Where it's asked

  • Apple · Technical phone screen · Last asked Feb 2026

What it tests

arrays · sorting · hash set

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding