easyTwo PointersPure DSA~12 min
Dedup Sorted Ledger
A sorted ledger of transaction amounts has consecutive duplicates from retried writes. Compact it in place so each amount appears once, and report how many unique entries remain.
Problem
Given a sorted integer array nums, remove the duplicates in place so each unique element appears once, keeping their relative order. Return k, the number of unique elements; the first k slots of nums must hold those elements.
Input
A non-decreasing sorted array nums of length n (0 ≤ n ≤ 3·10^4).
Output
An integer k; nums[0..k-1] hold the unique values in order.
Constraints
- Modify nums in place with O(1) extra space
- Input is sorted non-decreasing
- Order of unique values must be preserved
Examples
Example 1
Input
nums = [1, 1, 2]
Output
2 (nums starts with [1, 2])
One duplicate 1 is removed; two unique values remain.
Example 2
Input
nums = [0, 0, 1, 1, 1, 2, 2, 3]
Output
4 (nums starts with [0, 1, 2, 3])
Four distinct values remain in order.