Ctrl K

Squeeze Repeats Out of a Sorted Array

Easy
A sensor writes its readings into an array values, already sorted in non-decreasing order, so equal values sit next to each other. Remove the repeats right inside this array, without making a copy. Let k be the number of distinct values. Modify values so that its first k elements are those distinct values in their original order (that is, increasing). Whatever is left after the first k elements does not matter. Return k. Try to do it in one pass with O(1) extra memory.
Example 1
values=[-2, -2, 0, 5, 5, 5] → 3

There are three distinct values: -2, 0 and 5. The function returns 3 and the array starts with [-2, 0, 5, …].

Example 2
values=[7] → 1

A single element is already unique: the answer is 1.

Example 3
values=[1, 2, 2, 3, 3, 3, 4] → 4
Constraints
  • 1 ≤ len(values) ≤ 3·10⁴
  • -100 ≤ values[i] ≤ 100
  • values is sorted in non-decreasing order
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrop the Unwanted Value EasyMerge Into the Spare Tail EasyZeros to the Back EasyValues in Both Lists EasyShared Values With Repeats Easy
loading Python…
Input
values=[-2, -2, 0, 5, 5, 5]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 130 tests on the server, hidden ones included.