logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

80. Remove Duplicates from Sorted Array II

2 min read
On this pageIntuition
IntuitionApproachComplexityCode

Remove the duplicates in-place such that each unique element appears atmost twice. The relative order of the elements should be kept the same.

Input: nums = [1,1,2,2,2,2,2,3,3,3,3,3]
Output: 2, nums = [1,1,2,2,3,3]

Return the number of unique elements in nums.

Attention

Do not allocate extra space for another array. Achieve this by modifying the input array in-place with O(1)\text{O}(1)O(1) extra memory.


# Intuition

  • We can move an element forward by the amount of duplicates before it.

# Approach

  • We track the occurrence of an element.
  • Start moving the next elements forward only if the current elements occurrence is greater 2.

# Complexity

  • Time complexity : O(n)\text{O}(n)O(n)
    • We iterate the array only once
  • Space complexity : O(1)\text{O}(1)O(1)
    • We use no extra space, do operations in-place

# Code

public int removeDuplicates(int[] nums) {
 
	int occurence = 1,shift = 0;
 
	for (int i = 1; i < nums.length; ++i) {
		if(nums[i] == nums[i-1]) {
			occurence++;
			// only if there are more thantn 2 occurence
			// we can overwrite it  
			if(occurence > 2) {
				shift++;
				continue;
			}
		} else {
			// If the current element doesn't match the previous element
			// we reset the counter
			occurence = 1;
		}
		nums[i - shift] = nums[i];
	}
 
	return nums.length - shift;
}

Another Way

public int removeDuplicates(int[] nums) {
	// This tracks where the current element must be placed
	int i = 0;
	for (int n : nums)
		// If length is < 2 
		// If the current element is not equal to the element two 
		// places behind it
		if (i < 2 || n &gt; nums[i - 2])
	        nums[i++] = n;
	        
   return i;
}
←Previous55. Jump GameNext→88. Merge Sorted Array

On this page

IntuitionApproachComplexityCode