LeetCode 26. Remove Duplicates from Sorted Array

Description

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

Explanation

Since the array is already sorted, we can use two pointers technique, where i is the slow pointer while j is the fast pointer.

When nums[i] = nums[j], we increment faster pointer j to skip the duplicate.

When nums[j] != nums[i], we increment the slow pointer i and copy faster pointer place element value to slower pointer place.

Once j reaches the end of the array, all non duplicated elements were adjusted to the beginning of the array.

Video Tutorial

Java Solution

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int i = 0;
        
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }            
        }
        
        return i + 1;
        // Time Complextiy: O(n)
        // Space Complexity: O(1)
    }
}

One Thought to “LeetCode 26. Remove Duplicates from Sorted Array”

Leave a Reply

Your email address will not be published. Required fields are marked *