How to Solve Remove Duplicates from Array on LeetCode
Remove Duplicates from Array (often: from Sorted Array) is a classic in-place array challenge.
Problem Statement
Given a sorted array nums, remove the duplicates in-place such that each unique element appears only once. Return the new length. Do not allocate extra space for another array.
Example:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,...]
Why This Problem Matters for Interviews
- Tests in-place data manipulation
- Highlights two-pointer technique for arrays
- Often asked early in interview screens
Approach to Remove Duplicates from Array
Two-Pointer In-Place (Optimal)
Use two pointers: one for reading, one for writing unique values.
Time Complexity: O(n)
Space Complexity: O(1)
def removeDuplicates(nums):
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[read - 1]:
nums[write] = nums[read]
write += 1
return write
Key Interview Talking Points
- Why two pointers work for sorted arrays
- Clarify that extra array space is not allowed
- Output is the new length, not the full array
Big O Complexity Recap
Approach | Time Complexity | Space Complexity |
---|---|---|
Two Pointer | O(n) | O(1) |
Pro Interview Tips
- Practice with empty/one-element arrays
- Draw array after each write
- Explain why it only works for sorted input