Remove Duplicates from Sorted Array

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements.

More formally, if there are k unique elements, the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Examples

Example 1:

Input: nums = [1, 1, 2]

Output: 2

Explanation: The function returns k = 2, with the first two elements of nums being [1, 2].

Example 2:

Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]

Output: 5

Explanation: The function returns k = 5, with the first five elements of nums being [0, 1, 2, 3, 4].

Example 3:

Input: nums = [1, 2, 3]

Output: 3

Explanation: All elements are already unique, so k = 3 and nums remains [1, 2, 3].

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle