18. Remove Duplicates from Sorted Array
Remove repeated values logically by placing each distinct value once at the beginning of the same array. Return the number of values in this valid prefix.
Only the first k positions represent the required result. The contract does not require shortening the physical array or assigning meaningful values to the unused suffix.
Example 1
Input
[0,0,1,1,2]
Output
k=3, prefix=[0,1,2]
Explanation: Only the first three positions are meaningful after compaction.
Example 2
Input
[7,7,7]
Output
k=1, prefix=[7]
Explanation: One representative survives from the run.
Constraints
0 <= nums.length <= 105-231 <= nums[i] <= 231 - 1- nums is sorted in nondecreasing order. Return k and place the unique values in nums[0..k); the remaining tail is ignored.
Hints
Hint 1
What is the smallest state needed to recognize a new sorted run?
Hint 2
Let write be the number of unique values emitted so far.
Hint 3
Append only when the current value differs from nums[write-1].
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Compact three sorted runs
[0,0,1,1,2]
{"k":3,"prefix":[0,1,2]}