Practice Problem

Remove Duplicates from Sorted Array

Difficulty: Easy

Remove duplicates from a sorted array in-place so each element appears only once, and return the new length.

Remove Duplicates from Sorted Array

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Return the number of unique elements k. The first k elements of nums should hold the unique elements in their original order. Elements beyond index k do not matter.

Examples

Example 1:

Input: nums = [1, 1, 2]
Output: 2, nums = [1, 2, ...]
Explanation: The function returns k = 2, with the first 2 elements being 1 and 2.

Example 2:

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

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.

Expected Complexity

  • Time: O(n)
  • Space: O(1)
EASY
Arrays
Two Pointers
In-Place
Beginner

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium