Algorithm Day112 - Remove Duplicates from Sorted Array (lc-26)
LC-26 Remove Duplicates from Sorted Array
π Problem
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and return the new length. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.
π¬ Examples
Example 1
1 | Input: nums = [1,1,2] |
Example 2
1 | Input: nums = [0,0,1,1,1,2,2,3,3,4] |
π‘ Intuition (Two Pointers)
Because the array is sorted, duplicates are adjacent. Use two pointers β slow and fast:
slowtracks the position to write the next unique element (starts at 0).fastscans the array from 1 to end.- When
nums[fast] != nums[slow], incrementslowand copynums[fast]tonums[slow].
After the loop, the new length is slow + 1.
π’ Java Code (Two Pointers)
1 | class Solution { |
β± Complexity Analysis
- Time: O(n) β single pass through the array.
- Space: O(1) β in-place, constant extra space.
βοΈ Summary
- Use two pointers on a sorted array to overwrite duplicates.
- After processing, first
kelements are the unique values wherek = slow + 1. - Very common in interviews β demonstrates in-place array manipulation and two-pointer technique.