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

26. Remove Duplicates from Sorted Array

2 min read
On this pageIntuition
IntuitionApproachComplexityCode

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

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

Return the number of unique elements in nums.


# Intuition

  • A number is unique if nums[i] != nums[i-1]
  • If its not unique we can overwrite it with the next greater element.

# Approach

  • Start from the beginning with i=0 & j=0
    • i is fast points to current element & j is slow pointing to the previous element.
  • Only if the previous pointed element is not equal to the current element we increase j.
    • write current value in its place

# 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 do operation in-place, no extra space needed

# Code

public int removeDuplicates(int[] nums) {
	int j = 0;
 
	for (int i = 0; i < nums.length; ++i) {
		// If the element are not equal only then add to array
		if(nums[i] != nums[j]) {
			nums[++j] = nums[i];
		}
	}
	return j+1;
}

Alternate Solution

Count the number of places to shift each element

public int removeDuplicates(int[] nums) { 
	int shiftPlacesBy = 0; 
	for (int i = 1; i < nums.length; ++i) { 
		// if elements are equal we increase the shift count by
		if(nums[i] == nums[i-1]) { 
			shiftPlacesBy++; 
			continue; 
		} 
		nums[i - shiftPlacesBy] = nums[i]; 
	} 
	return nums.length - shiftPlacesBy; 
} 
Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(n)\text{O}(n)O(n)
  • we iterate the array only once
  • we do operation in-place, no extra space needed
←Previous25. Reverse Nodes in k-GroupNext→27. Remove Element

On this page

IntuitionApproachComplexityCode