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
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

26. Remove Duplicates from Sorted Array

1 min read
On this pageIntitution
IntitutionComplexityCode

# Intitution

In a sorted array, duplicates are always next to each other. So use a slow and fast pointer where the slow only moves when an unique element is encountered. Just scan through the array, and whenever we see a new (unique) element, overwrite the front part of the array with it, maintaining only the distinct values in-place.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(n)\text{O}(n)O(n)

# Code

public int removeDuplicates(int[] nums) {
    int i = 0, j = 0;
 
    // Traverse the array
    for(; i < nums.length;) {
        // If first element or current is not equal to the previous (i.e., it's unique)
        if(i == 0 || nums[i-1] != nums[i]) {
            nums[j] = nums[i];  // Place the unique element at the next available position
            j++;                // Move the insert pointer
        }
        i++; // Move to the next element
    }
 
    return j; // j is the new length of the array with unique elements
}
←Previous20. Valid ParenthesesNext→35. Search Insert Position

On this page

IntitutionComplexityCode