Remove Duplicates from Sorted Array

Problem Statement: (link)

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns 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.

Note that the input array is passed in by reference, which means a modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
Code language: C++ (cpp)
  • 0 <= nums.length <= 3 * 104
  • -104 <= nums[i] <= 104
  • nums is sorted in ascending order.

Code Solution:

Since the array is already sorted, we can keep two pointers and j, where i is the slow-runner while is the fast-runner. As long as nums[i] = nums[j], we increment j to skip the duplicate.

When we encounter nums[j]​≠nums[i], the duplicate run has ended so we must copy its value to nums[i+1]. i is then incremented and we repeat the same process again until j reaches the end of array.

Solution in C++

class Solution { public: int removeDuplicates(vector<int>& nums) { nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); return nums.size(); } };
Code language: C++ (cpp)

Solution in Java

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

Solution in Python

class Solution: def removeDuplicates(self, nums): len_ = 1 if len(nums)==0: return 0 for i in range(1,len(nums)): if nums[i] != nums[i-1]: nums[len_] = nums[i] len_ +=1 return len_
Code language: Python (python)

Complexity analysis

  • Time complextiy : O(n). Assume that n is the length of array. Each of i and j traverses at most n steps.
  • Space complexity : O(1).

No post found!

Want to Contribute:-

If you like “To The Innovation” and want to contribute, you can mail your articles to 📧 See your articles on the main page and help other coders.😎

Leave a Comment

Your email address will not be published.