Compress Sorted Array to Unique Elements
Arrays & HashingAuto-graded · 23 test casesLast 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:
- The count of unique elements
- 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that because the array is sorted, all duplicate values are grouped together consecutively. This means we can identify unique values by comparing each element with the last unique value we've already processed.
We use a two-pointer technique:
- A read pointer that scans through every element from left to right
- A write pointer that tracks the position where the next unique value should be placed
The first element is always unique, so we initialize the write pointer to position 1. For each subsequent element at the read position:
- If it differs from the last unique value we kept (at
write - 1), it's a new unique value. We copy it to the write position and advance the write pointer. - If it equals the last unique value, it's a duplicate and we skip it.
The write pointer always stays at or behind the read pointer (write ≤ read), ensuring we never overwrite data we haven't yet examined.
Why It Works
We maintain this invariant: before processing position read, the subarray nums[0:write] contains exactly the unique values from nums[0:read] in sorted order with no duplicates.
Initially with read = 1 and write = 1, the single-element prefix contains the unique values from the first element—trivially true.
At each step, since the array is sorted, nums[read] ≥ nums[write - 1]. If they're equal, we already have this value in our unique prefix. If they differ, nums[read] is strictly larger than all kept values, so it's new and we append it.
When the scan completes, the prefix contains all unique values from the entire array.
Complexity
Time complexity: O(n) where n is the length of the array. We make a single pass through the array, performing constant work at each position.
Space complexity: O(1) extra space. We only use two integer pointers for the algorithm itself. The returned slice creates a copy of the result for output purposes, but the core algorithm modifies the array in-place without additional memory.
Edge Cases
- Empty array: Return
[0, []]immediately - Single element: The loop doesn't execute, return
[1, [element]] - All elements identical: Only the first is kept, return
[1, [value]] - All elements unique: Each element is written to its own position, return
[n, original_array]
from typing import List
def compress_sorted_array(nums: List[int]) -> List:
if not nums:
return [0, []]
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return [write, nums[:write]]