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)];
}

Was this page helpful?