Remove Duplicates from Sorted Array LeetCode 26

Problem :- Remove Duplicates from Sorted Array (LeetCode 26) Problem Statement :- Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements. The relative order of elements should be kept the same. Approach :- Two Pointer Technique i - Use pointer k to track position of unique elements ii - Traverse array from index 1 iii - If nums[i] != nums[k-1], place it at nums[k] iv - Time Complexity : O(n) v - Space Complexity : O(1) class Solution {    public int removeDuplicates(int[] nums) {      int k = 1;      for(int i = 1; i < nums.length; i++) {        if(nums[i] != nums[k - 1]) {          nums[k] = nums[i];          k++;       }      }      return k;   } } Key Takeaway :- Since the array is already sorted, duplicates are adjacent. Using two pointers allows us to efficiently overwrite duplicates in a single pass without extra space. If yes, how would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #TwoPointers

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories