CodingNeed.
Fresher · Arrays & hashing

Remove Duplicate Values

Return the unique numbers from an array in their original order. Do not mutate the input.

Examples

[1, 2, 1, 3, 2] → [1, 2, 3]

Compare approaches

Linear search

Repeated membership scans are simple but can be quadratic.

Time: O(n²) · Space: O(n)

function unique(nums) {
  const result = [];
  for (const n of nums) if (!result.includes(n)) result.push(n);
  return result;
}
Set

Set preserves insertion order and has expected constant-time insertion.

Time: O(n) expected · Space: O(n)

function unique(nums) {
  return [...new Set(nums)];
}

Common traps

  • Preserve first occurrence order.
  • Do not sort or mutate the input.
Practise in the workspace →

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.