Finding two missing numbers that appears only once and twice respectively in JavaScript

We need to write a JavaScript function that finds two numbers in an array where all other numbers appear three times, except one number that appears twice and another that appears only once.

Problem Statement

Given an array where most numbers appear three times, find the two numbers that appear exactly twice and exactly once respectively.

Example

Let's solve this step by step:

const arr = [1, 1, 1, 2, 2, 3];

const findMissing = (arr = []) => {
    let x = 0; // number appearing once
    let y = 0; // number appearing twice
    
    for (let i = 0; i  num === arr[i]).length;
        
        if (count === 2) {
            y = arr[i];
        }
        if (count === 1) {
            x = arr[i];
        }
    }
    
    return [x, y];
};

console.log(findMissing(arr));
[3, 2]

Optimized Solution Using Map

A more efficient approach uses a Map to count occurrences in a single pass:

const findMissingOptimized = (arr = []) => {
    const countMap = new Map();
    
    // Count occurrences
    for (const num of arr) {
        countMap.set(num, (countMap.get(num) || 0) + 1);
    }
    
    let once = 0, twice = 0;
    
    // Find numbers with specific counts
    for (const [num, count] of countMap) {
        if (count === 1) once = num;
        if (count === 2) twice = num;
    }
    
    return [once, twice];
};

const testArray = [4, 4, 4, 5, 5, 6, 7, 7, 7];
console.log(findMissingOptimized(testArray));
[6, 5]

Comparison

Approach Time Complexity Space Complexity
Filter Method O(n²) O(1)
Map Method O(n) O(n)

How It Works

The first solution filters the array for each element to count occurrences. The optimized version uses a Map to count all occurrences in one pass, then finds the numbers with counts of 1 and 2.

Conclusion

Both solutions work correctly, but the Map-based approach is more efficient for larger arrays. Use the filter method for simplicity or the Map method for better performance.

Updated on: 2026-03-15T23:19:00+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements