⚡ TL;DR
Solve Remove Duplicates from Sorted Array in Swift with working code. Two Pointers (Optimal) approach with O(n) time, plus complexity analysis and interview tips.
Remove Duplicates from Sorted Array (#26 — Easy): Given a sorted integer array nums, remove duplicates in-place such that each unique element appears only once. Return the number of unique elements.
Problem Statement
Given a sorted integer array nums, remove duplicates in-place such that each unique element appears only once. Return the number of unique elements.
Example:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]Approach: Two Pointers (Optimal)
Time: O(n) | Space: O(1)
One read pointer scans all elements; one write pointer only advances when it finds a new unique value. Since the array is sorted, duplicates are always adjacent.
func removeDuplicates(_ nums: inout [Int]) -> Int {
guard !nums.isEmpty else { return 0 }
var write = 1
for read in 1..<nums.count {
if nums[read] != nums[read - 1] {
nums[write] = nums[read]
write += 1
}
}
return write
}
var nums = [1,1,2,2,3]
let k = removeDuplicates(&nums)
print(k, Array(nums[0..<k])) // 3 [1, 2, 3]Key Takeaways
- Start with the brute-force approach to understand the problem
- Two Pointers (Optimal) gives the optimal O(n) solution
- Practice this pattern — it appears frequently in coding interviews
Related Problems
- Remove Duplicates from Sorted Array in Python
- Remove Duplicates from Sorted Array in Dart
- Remove Duplicates from Sorted Array in Go
- Two Sum in Swift
- Maximum Subarray in Swift
- Linked List Cycle in Swift
FAQ
What is the best approach to solve Remove Duplicates from Sorted Array in Swift?
The recommended approach is Two Pointers (Optimal), which runs in O(n) time with O(1) space. The full Swift implementation is shown above.
What is the time complexity of Remove Duplicates from Sorted Array in Swift?
Using Two Pointers (Optimal), the time complexity is O(n) and the space complexity is O(1).
Happy coding!
