AceYourInterviews
Checking sign-in…

18. Remove Duplicates from Sorted Array

IntermediateRead/write compaction of sorted runs

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].

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Compact three sorted runs

[0,0,1,1,2]
{"k":3,"prefix":[0,1,2]}