Coding problem · Easy · Basics
Remove Duplicates (Keep Order)
Easy Algorithms & data structures
Return a new array with duplicate values removed, keeping the first occurrence of each value and the original order.
Example 1
Input: nums = [3,1,3,2,1] Output: [3,1,2]
Example 2
Input: nums = [7,7,7] Output: [7]
Hints
Hint 1
Remember which values you've already added, in a set.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(n)
Walk through the array and add each value to the output only if it isn't in the seen set yet. A set makes each check O(1).
Reference solution
function removeDuplicates(nums) {
return [...new Set(nums)];
}
function removeDuplicates(nums: number[]): number[] {
return [...new Set(nums)];
}
def remove_duplicates(nums: list[int]) -> list[int]:
seen, out = set(), []
for n in nums:
if n not in seen:
seen.add(n)
out.append(n)
return out
<?php
function removeDuplicates(array $nums): array
{
return array_values(array_unique($nums));
}
class Solution {
public int[] removeDuplicates(int[] nums) {
java.util.LinkedHashSet<Integer> seen = new java.util.LinkedHashSet<>();
for (int n : nums) seen.add(n);
return seen.stream().mapToInt(Integer::intValue).toArray();
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy