LeetCode 26: Remove Duplicates from Sorted Array Solution

Master LeetCode problem 26 (Remove Duplicates from Sorted Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

26. Remove Duplicates from Sorted Array

Problem Explanation

Explanation:

To solve this problem, we can use a two-pointer approach where one pointer will iterate over the array, and the other pointer will keep track of the position where the next unique element should be placed. As the array is already sorted, duplicate elements will be adjacent to each other. We can compare the current element with the next element and only move the unique elements to the front of the array.

  • Initialize two pointers: i for iterating over the array and j for placing unique elements.
  • Iterate over the array from index 1 to the end.
  • If the current element is different from the previous element, place it at index j and increment j.
  • After iterating, the first j elements will contain the unique elements.
  • Return the value of j as the number of unique elements.

Time Complexity: O(n) where n is the number of elements in the array.

Space Complexity: O(1) as we are using constant extra space.

Solution Code

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        
        int j = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[i - 1]) {
                nums[j] = nums[i];
                j++;
            }
        }
        
        return j;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 26 (Remove Duplicates from Sorted Array)?

This page provides optimized solutions for LeetCode problem 26 (Remove Duplicates from Sorted Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 26 (Remove Duplicates from Sorted Array)?

The time complexity for LeetCode 26 (Remove Duplicates from Sorted Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 26 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 26 in Java, C++, or Python.

Back to LeetCode Solutions