Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Remove Duplicates from Sorted Array

Problem Statement

Given a sorted array of integers, remove duplicates in-place such that each unique element appears only once. Return the new length of the array. The relative order of elements should be preserved, and the operation must be done with O(1) extra space. This is an easy-level problem focusing on array manipulation.

Example

Input: nums = [1, 1, 2]

Output: 2 (array becomes [1, 2], length = 2)

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

Output: 5 (array becomes [0, 1, 2, 3, 4], length = 5)

Code

Java
Python
JavaScript
public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        
        int uniquePos = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i - 1]) {
                nums[uniquePos] = nums[i];
                uniquePos++;
            }
        }
        return uniquePos;
    }
}
            
def remove_duplicates(nums):
    if not nums:
        return 0
        
    unique_pos = 1
    for i in range(1, len(nums)):
        if nums[i] != nums[i - 1]:
            nums[unique_pos] = nums[i]
            unique_pos += 1
    return unique_pos

# Example usage
nums1 = [1, 1, 2]
print(remove_duplicates(nums1), nums1[:remove_duplicates(nums1)])  # 2, [1, 2]
nums2 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
print(remove_duplicates(nums2), nums2[:remove_duplicates(nums2)])  # 5, [0, 1, 2, 3, 4]
            
function removeDuplicates(nums) {
    if (nums.length === 0) return 0;
    
    let uniquePos = 1;
    for (let i = 1; i < nums.length; i++) {
        if (nums[i] !== nums[i - 1]) {
            nums[uniquePos] = nums[i];
            uniquePos++;
        }
    }
    return uniquePos;
}

// Example usage
let nums1 = [1, 1, 2];
console.log(removeDuplicates(nums1), nums1.slice(0, removeDuplicates(nums1))); // 2, [1, 2]
let nums2 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
console.log(removeDuplicates(nums2), nums2.slice(0, removeDuplicates(nums2))); // 5, [0, 1, 2, 3, 4]
            

Explanation

  • Handle the empty array case by returning 0.
  • Use a pointer (uniquePos) to track the position for the next unique element.
  • Iterate through the array starting from the second element.
  • If the current element differs from the previous one, place it at uniquePos and increment the pointer.
  • Return the final value of uniquePos, which is the length of the unique portion.

Note

Time complexity is O(n) where n is the array length. Space complexity is O(1) as it modifies the array in-place.