Remove Duplicates from Sorted Array

Difficulty: Easy · Topics: Array, Two Pointers, In-place

Difficulty: Easy  |  Tags: Array, Two Pointers, In-place

Description

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 k. The first k elements of nums should hold the result.

Implement:

removeDuplicates(nums) → int

Examples

Example 1:

Input:  nums = [1, 1, 2]
Output: k = 2, nums = [1, 2, _]

Example 2:

Input:  nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: k = 5, nums = [0, 1, 2, 3, 4, _, _, _, _, _]

Example 3:

Input:  nums = [1]
Output: k = 1, nums = [1]

Constraints

Hints

Hint 1

Use two pointers: a slow pointer for the write position, a fast pointer for scanning.

Practice this problem

Related problems