
Remove Duplicates from Sorted Array II (LeetCode 80) — Simple Explanation
This problem is a great extension of the basic two-pointer technique. Problem Understanding We are given a sorted array. -> We must remove duplicates in-place -> But each element can appear at most twice Example Input: -> [1,1,1,2,2,3] Output: -> [1,1,2,2,3] Return: -> k = 5 Idea (Very Simple) We use two pointers: j -> reads elements k -> writes valid elements Key Condition if (k < 2 || nums[j] != nums[k - 2]) What does this mean? First 2 elements are always allowed After that: Compare current element with 2 positions before If same -> skip If different -> include Why k - 2? Because we allow maximum 2 duplicates so we check “Did we already take this number twice?” C++ Code class Solution { public: int removeDuplicates ( vector < int >& nums ) { int k = 0 ; for ( int j = 0 ; j < nums . size (); j ++ ) { if ( k < 2 || nums [ j ] != nums [ k - 2 ]) { nums [ k ] = nums [ j ]; k ++ ; } } return k ; } }; Dry Run (Important) Input: -> [1,1,1,2,2,3] j nums[j] k Action Result 0 1 0 take [1] 1 1
Continue reading on Dev.to Beginners
Opens in a new tab




