KatInterview

Compress Sorted Array to Unique Elements

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersin-placesorted-array

Last updated

Tests in-place array manipulation with two-pointer technique to remove duplicates from a sorted sequence.

You are given a sorted array of integers in non-decreasing order. Modify the array in-place to remove all duplicate values, keeping only the first occurrence of each unique element. The relative order of unique elements must remain unchanged.

Return a list containing two items:

  1. The count of unique elements
  2. A list of the unique elements in their original order

After your modification, the first k positions of the input array should contain the unique elements, where k is the count you return. The contents of the array beyond position k do not matter.

Constraints

  • 0 ≤ array length ≤ 10⁵
  • -10⁹ ≤ array[i] ≤ 10⁹
  • The input array is sorted in non-decreasing order
  • You must modify the array in-place using O(1) extra space
  • Your algorithm should run in O(n) time

Examples

Example 1

Input: compress_sorted_array([1, 1, 2])

Output: [2, [1, 2]]

Example 2

Input: compress_sorted_array([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])

Output: [5, [0, 1, 2, 3, 4]]

Example 3

Input: compress_sorted_array([1])

Output: [1, [1]]

Example 4

Input: compress_sorted_array([])

Output: [0, []]

Hints

Hint 1

Since the array is sorted, all duplicates of a value are adjacent to each other.

Hint 2

Use two pointers: one to read through all elements, and one to track where to write the next unique value.

Hint 3

Compare each element with the last unique value you've kept, not with its immediate predecessor in the input.