#26
Remove Duplicates from Sorted Array
EasyArrayTwo PointersHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Two Pointers)★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses two pointers to track the position of unique elements and the current element being examined. This allows us to efficiently overwrite duplicates in the original array without using extra space.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a pointer `k` to 1 (the position for the next unique element).
- 2Step 2: Iterate through the array starting from the second element.
- 3Step 3: If the current element is different from the previous one, assign it to the position `k` and increment `k`.
solution.py11 lines
1# Full working Python code with comments
2
3def removeDuplicates(nums):
4 if not nums:
5 return 0
6 k = 1 # Pointer for the next unique element
7 for i in range(1, len(nums)):
8 if nums[i] != nums[i - 1]:
9 nums[k] = nums[i] # Update position k with unique element
10 k += 1 # Move to next position
11 return kℹ
Complexity note: This complexity is linear because we make a single pass through the array, updating it in place without needing extra space.
- 1The sorted nature of the array allows us to use a two-pointer technique effectively, as duplicates will always be adjacent.
- 2In-place modification is crucial to meet the problem's constraints, which means we should avoid using additional data structures.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.