⚡ TL;DR
Solve Remove Duplicates from Sorted Array in Go 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 []int) int {
if len(nums) == 0 { return 0 }
write := 1
for read := 1; read < len(nums); read++ {
if nums[read] != nums[read-1] {
nums[write] = nums[read]
write++
}
}
return write
}
func main() {
nums := []int{1,1,2,2,3}
k := removeDuplicates(nums)
fmt.Println(k, nums[: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 Swift
- Two Sum in Go
- Maximum Subarray in Go
- Linked List Cycle in Go
FAQ
What is the best approach to solve Remove Duplicates from Sorted Array in Go?
The recommended approach is Two Pointers (Optimal), which runs in O(n) time with O(1) space. The full Go implementation is shown above.
What is the time complexity of Remove Duplicates from Sorted Array in Go?
Using Two Pointers (Optimal), the time complexity is O(n) and the space complexity is O(1).
Happy coding!
