CodingEasy Arrays & Hashing

Remove Duplicates from an Array

Asked for all developer roles

Why they ask this: Checks basic use of sets or hash maps, and whether you think about preserving order.

Problem

Given an array of integers, return a new array with duplicates removed, keeping the first occurrence of each value in its original order. Try it without a one-line built-in first.

Example

text
Input:  [3, 1, 3, 2, 1, 4]
Output: [3, 1, 2, 4]

Follow-up: if the array is already sorted, can you remove duplicates in place using O(1) extra space?

Hints

    Approach

    Walk through the array once with a seen set. If a value is not in the set, add it to the set and push it to the result; otherwise skip it. Order is preserved because you only ever append the first occurrence.

    Sorted, in place: keep write = 1. For each i from 1, if nums[i] !== nums[write - 1], copy it to nums[write] and increment write. The first write elements are the unique values.

    In real code, [...new Set(arr)] (JavaScript) and array_values(array_unique($arr)) (PHP) do the same job. Note that array_unique compares values as strings, so 1 and "1" count as duplicates.

    Solution

    js
    function removeDuplicates(nums) {
      const seen = new Set();
      const result = [];
    
      for (const num of nums) {
        if (!seen.has(num)) {
          seen.add(num);
          result.push(num);
        }
      }
    
      return result;
    }
    
    console.log(removeDuplicates([3, 1, 3, 2, 1, 4])); // [3, 1, 2, 4]
    Time O(n) Space O(n)

    Can you explain this in your own words?

    Back to coding practice