Remove Duplicates from Sorted Array solution and explanation
9 more videos on this problem
Remove Duplicates from Sorted Array - Leetcode 26 - PythonNeetCode · 10:38 · 325K views
Remove Duplicates from Sorted Array | Leetcode 26 | Top 150 interview question seriesTechnosage · 9:08 · 101K views
How To Remove Duplicates From Sorted Array ( LeetCode 26 ) | FREE DSA Course in JAVA | Lecture 65TAP ACADEMY · 18:12 · 91K views
Remove Duplicates From Sorted Array - Leetcode 26 - Arrays & Strings (Python)Greg Hogg · 4:59 · 28K views
LeetCode 26: Remove Duplicates From a Sorted ArrayAbstracted Away · 3:26 · 15K views
Remove Duplicates from Sorted Array - Leetcode 26 - JavaMastering Programming · 4:38 · 6K views
LeetCode Problem: 26. Remove Duplicates from Sorted Array | Java SolutionCode for Interview · 13:27 · 5K views
Remove Duplicates from Sorted Array | LeetCode 26 | JavaTech Tutor · 9:06 · 4K views
Remove Duplicates From Sorted Array | LeetCode 26Destination FAANG · 7:44 · 888 views
26. Remove Duplicates from Sorted Array (Python) | LeetcodeQuoc Dat Phung · 5:57 · 643 views
The problem
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
- Change the array
numssuch that the firstkelements ofnumscontain the unique elements in the order they were present innumsinitially. The remaining elements ofnumsare not important as well as the size ofnums. - Return
k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2] Output: 2, nums = [1,2,_] Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 104-100 <= nums[i] <= 100numsis sorted in non-decreasing order.
Approach overview
Problem Overview: You receive a sorted integer array and must remove duplicate values in-place so each element appears only once. The function returns the number of unique elements while keeping the first k positions of the array filled with those unique values.
Approach 1: Simple In-Place Overwrite Technique (O(n) time, O(1) space)
The array is already sorted, which means duplicates always appear next to each other. Iterate through the array while tracking the last unique value you wrote. When the current element differs from the previous unique value, overwrite the next position in the array with that element. This effectively compacts unique values toward the front while skipping duplicates. The algorithm performs a single linear pass with constant extra memory, making it ideal for problems that require in-place modification of an array.
Approach 2: Two-Pointer Technique (O(n) time, O(1) space)
This approach uses two indices: a read pointer that scans the array and a write pointer that marks the position for the next unique element. Start both at the beginning. As the read pointer iterates, compare nums[read] with the previous element. When they differ, increment the write pointer and copy the value there. Because the input is sorted, this comparison reliably detects duplicates without additional structures like hash sets. This pattern is a classic two pointers optimization for ordered data structures and keeps the solution linear with constant memory.
The key insight is that sorted order groups duplicates together. Instead of removing elements (which would require shifting many values), you simply overwrite positions with the next distinct number encountered. Every element is processed once, so runtime stays proportional to the array size.
Recommended for interviews: Interviewers expect the two-pointer solution. It demonstrates that you recognize the sorted property and can optimize the algorithm to O(n) time with O(1) space. Writing the overwrite logic clearly shows you understand in-place operations and pointer movement. A naive removal approach with repeated shifting works conceptually but performs unnecessary operations and does not demonstrate the same level of algorithmic efficiency.
Approach 1: Two-Pointer Technique
The two-pointer technique is an efficient way to solve this problem in-place. We initialize two pointers, where one (called slow) tracks the position of unique elements, and the other (called fast) traverses the entire array.
Whenever we find a new unique element using the fast pointer, we move the slow pointer one step forward and place the unique element at that position. This way, the array elements from index 0 to the slow pointer are all unique.
def removeDuplicates(nums):
if not nums:
return 0
j = 0
for i in range(1, len(nums)):
if nums[i] != nums[j]:
j += 1
nums[j] = nums[i]
return j + 1
nums = [0,0,1,1,1,2,2,3,3,4]
k = removeDuplicates(nums)
print(f"{k}, nums = {nums[:k]}")public class RemoveDuplicates {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int j = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
public static void main(String[] args) {
RemoveDuplicates solution = new RemoveDuplicates();
int[] nums = {0,0,1,1,1,2,2,3,3,4};
int k = solution.removeDuplicates(nums);
System.out.print(k + ", nums = [");
for (int i = 0; i < k; i++) {
System.out.print(nums[i] + (i < k - 1 ? "," : ""));
}
System.out.println("]");
}
}#include <vector>
using namespace std;
int removeDuplicates(vector<int>& nums) {
if (nums.size() == 0) return 0;
int j = 0;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let j = 0;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
let nums = [0,0,1,1,1,2,2,3,3,4];
let k = removeDuplicates(nums);
console.log(`${k}, nums = [${nums.slice(0, k).join(',')}]`);#include <stdio.h>
int removeDuplicates(int* nums, int numsSize) {
if (numsSize == 0) return 0;
int j = 0;
for (int i = 1; i < numsSize; i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
int main() {
int nums[] = {0,0,1,1,1,2,2,3,3,4};
int size = sizeof(nums) / sizeof(nums[0]);
int k = removeDuplicates(nums, size);
printf("%d, nums = [", k);
for (int i = 0; i < k; i++) {
printf("%d%s", nums[i], (i == k - 1) ? "" : ",");
}
printf("]\n");
return 0;
}public class Solution {
public int RemoveDuplicates(int[] nums) {
if (nums.Length == 0) return 0;
int j = 0;
for (int i = 1; i < nums.Length; i++) {
if (nums[i] != nums[j]) {
j++;
nums[j] = nums[i];
}
}
return j + 1;
}
public static void Main(string[] args) {
var solution = new Solution();
int[] nums = {0,0,1,1,1,2,2,3,3,4};
int k = solution.RemoveDuplicates(nums);
Console.WriteLine($"{k}, nums = [{string.Join(",", nums.Take(k))}]");
}
}In Python, we iterate using a for loop and compare each element with the last found unique element. The unique elements are stored in place, updating the existing array.
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: Simple In-Place Overwrite Technique
An alternative approach without pointers uses a simple loop to iterate over the array and compare each element with the previous one. The still unique elements overwrite duplicate positions directly in the initial part of the array.
def removeDuplicates(nums):
j = 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
nums[j] = nums[i]
j += 1
return j if nums else 0
nums = [0,0,1,1,1,2,2,3,3,4]
k = removeDuplicates(nums)
print(f"{k}, nums = {nums[:k]}")public class RemoveDuplicates {
public int removeDuplicates(int[] nums) {
int j = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i - 1]) {
nums[j] = nums[i];
j++;
}
}
return (nums.length > 0) ? j : 0;
}
public static void main(String[] args) {
RemoveDuplicates solution = new RemoveDuplicates();
int[] nums = {0,0,1,1,1,2,2,3,3,4};
int k = solution.removeDuplicates(nums);
System.out.print(k + ", nums = [");
for (int i = 0; i < k; i++) {
System.out.print(nums[i] + (i < k - 1 ? "," : ""));
}
System.out.println("]");
}
}#include <vector>
using namespace std;
int removeDuplicates(vector<int>& nums) {
int j = 1;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] != nums[i - 1]) {
nums[j] = nums[i];
j++;
}
}
return (!nums.empty()) ? j : 0;
}function removeDuplicates(nums) {
let j = 1;
for (let i = 1; i < nums.length; i++) {
if (nums[i] !== nums[i - 1]) {
nums[j] = nums[i];
j++;
}
}
return nums.length ? j : 0;
}
let nums = [0,0,1,1,1,2,2,3,3,4];
let k = removeDuplicates(nums);
console.log(`${k}, nums = [${nums.slice(0, k).join(',')}]`);#include <stdio.h>
int removeDuplicates(int* nums, int numsSize) {
int j = 1;
for (int i = 1; i < numsSize; i++) {
if (nums[i] != nums[i - 1]) {
nums[j] = nums[i];
j++;
}
}
return (numsSize > 0) ? j : 0;
}
int main() {
int nums[] = {0,0,1,1,1,2,2,3,3,4};
int size = sizeof(nums) / sizeof(nums[0]);
int k = removeDuplicates(nums, size);
printf("%d, nums = [", k);
for (int i = 0; i < k; i++) {
printf("%d%s", nums[i], (i == k - 1) ? "" : ",");
}
printf("]\n");
return 0;
}public class Solution {
public int RemoveDuplicates(int[] nums) {
int j = 1;
for (int i = 1; i < nums.Length; i++) {
if (nums[i] != nums[i - 1]) {
nums[j] = nums[i];
j++;
}
}
return (nums.Length > 0) ? j : 0;
}
public static void Main(string[] args) {
var solution = new Solution();
int[] nums = {0,0,1,1,1,2,2,3,3,4};
int k = solution.RemoveDuplicates(nums);
Console.WriteLine($"{k}, nums = [{string.Join(",", nums.Take(k))}]");
}
}The Python code iterates over the sorted list, shifting elements to occupy positions denoted by the variable j upon encountering unique elements.
Time Complexity: O(n)
Space Complexity: O(1)
Approach 3: Single Pass
We use a variable k to record the current length of the processed array. Initially, k=0 represents an empty array.
Then we traverse the array from left to right. For each element x we encounter, if k=0 or x neq nums[k-1], we place x in the position of nums[k], and then increment k by 1. Otherwise, x is the same as nums[k-1], so we skip this element. Continue to traverse until the entire array is traversed.
In this way, when the traversal ends, the first k elements in nums are the answer we are looking for, and k is the length of the answer.
The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the array.
Supplement:
The original problem requires that the same number appear at most once. We can extend it to keep at most k identical numbers.
- Since the same number can be kept at most
ktimes, we can directly keep the firstkelements of the original array; - For the following numbers, the premise of being able to keep them is: the current number
xis compared with the lastkth element of the previously retained numbers. If they are different, keep them, otherwise skip them.
Similar problems:
function removeDuplicates(nums: number[]): number {
let k: number = 0;
for (const x of nums) {
if (k === 0 || x !== nums[k - 1]) {
nums[k++] = x;
}
}
return k;
}func removeDuplicates(nums []int) int {
k := 0
for _, x := range nums {
if k == 0 || x != nums[k-1] {
nums[k] = x
k++
}
}
return k
}impl Solution {
pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
let mut k = 0;
for i in 0..nums.len() {
if k == 0 || nums[i] != nums[k - 1] {
nums[k] = nums[i];
k += 1;
}
}
k as i32
}
}class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function removeDuplicates(&$nums) {
$k = 0;
foreach ($nums as $x) {
if ($k == 0 || $x != $nums[$k - 1]) {
$nums[$k++] = $x;
}
}
return $k;
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two-Pointer Technique | Time Complexity: O(n) Space Complexity: O(1) |
| Simple In-Place Overwrite Technique | Time Complexity: O(n) Space Complexity: O(1) |
| Single Pass | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Simple In-Place Overwrite | O(n) | O(1) | When the array is sorted and duplicates appear consecutively |
| Two-Pointer Technique | O(n) | O(1) | Preferred interview approach for in-place array modification |
Frequently asked questions
Is Remove Duplicates from Sorted Array easy or hard?
Remove Duplicates from Sorted Array is classified as an Easy problem on LeetCode. The challenge mainly involves recognizing the sorted property and applying a two-pointer strategy to modify the array in-place efficiently.
Remove Duplicates from Sorted Array Python/Java solution
Both Python and Java implementations follow the same two-pointer pattern. Iterate through the array, compare each element with the previous one, and overwrite the next position for unique values. The algorithm maintains O(n) time complexity and O(1) extra space regardless of the programming language.
How to solve Remove Duplicates from Sorted Array in O(n)?
Iterate through the sorted array with a read pointer while maintaining a write pointer for the position of the next unique value. When the current element differs from the previous element, move the write pointer forward and copy the value there. This ensures every unique number appears once at the start of the array while completing the scan in linear time.
What is the best approach for Remove Duplicates from Sorted Array?
The best approach uses the two-pointer technique. One pointer scans the array while another tracks the position for the next unique element. Because the array is sorted, duplicates appear consecutively and can be skipped with a simple comparison. This method runs in O(n) time and uses O(1) extra space.
Is Remove Duplicates from Sorted Array asked at Google/Amazon/Meta?
Remove Duplicates from Sorted Array is a common entry-level interview problem and has appeared in screening rounds at companies like Google, Amazon, and Meta. It tests understanding of in-place array manipulation, pointer movement, and recognizing when sorted properties simplify duplicate detection.
What data structure is used in Remove Duplicates from Sorted Array?
The problem primarily uses arrays with the two-pointer technique. Since the input array is sorted, duplicate detection relies on comparing adjacent elements rather than using additional structures like hash sets.
What is the time complexity of Remove Duplicates from Sorted Array?
The optimal solution runs in O(n) time because the array is scanned once from left to right. Each element is compared with the previous unique value and written at most once. Space complexity remains O(1) since the algorithm modifies the array in-place without extra data structures.
