Algo-Sim › Two Pointers
Remove Duplicates from Sorted Array
Easy · Two Pointers · step through it in Java, Python and C++ on your own input
Compact a sorted array in place so each value appears once, and return how many unique values there are.
Problem
Given an integer array nums sorted in non-decreasing order, rearrange it in place so that each distinct value appears once, in the original order, at the front of the array. Return k, the number of distinct values; whatever is left after the first k positions does not matter.
Constraints
- 1 ≤ nums.length ≤ 3 · 10⁴
- -100 ≤ nums[i] ≤ 100
- nums is sorted in non-decreasing order
- In place, O(1) extra space
Edge cases to test
- Empty array:
0 - All equal
- Already unique
Follow-up questions
- What if each value may appear at most twice?
- Compare with the element two places back in the written part: write
nums[i]if it differs fromnums[k − 2](LC 80). Same O(n), O(1). - What if the array is not sorted?
- Use a hash set to drop repeats, or sort first: O(n) with O(n) space, or O(n log n) in place.
Solution
Java
public int removeDuplicates(int[] nums) {
int write = 1;
for (int read = 1; read < nums.length; read++) {
if (nums[read] != nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}Python
def remove_duplicates(nums):
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
return writeC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int> &nums) {
int write = 1;
for (int read = 1; read < int(nums.size()); read++) {
if (nums[read] != nums[write - 1]) {
nums[write] = nums[read];
write++;
}
}
return write;
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)