Finding the missing number between two arrays of literals in JavaScript

Finding the missing number between two arrays is a common programming problem where one array is a shuffled version of another with exactly one element removed.

Problem Statement

We need to write a JavaScript function that takes two arrays: arr1 (original) and arr2 (shuffled duplicate with one missing element). The function should identify and return the missing element.

Example

const arr1 = [6, 1, 3, 6, 8, 2];
const arr2 = [3, 6, 6, 1, 2];

const findMissing = (arr1 = [], arr2 = []) => {
    const obj = {};
    
    // Count occurrences of each element in arr1
    for (let i = 0; i < arr1.length; i++) {
        if (obj[arr1[i]] === undefined) {
            obj[arr1[i]] = 1;
        } else {
            obj[arr1[i]]++;
        }
    }
    
    // Decrement count for each element in arr2
    for (let i = 0; i < arr2.length; i++) {
        if (obj[arr2[i]] === undefined || obj[arr2[i]]-- === 0) {
            return arr2[i];
        }
    }
    
    // Find the remaining element with count > 0
    for (let key in obj) {
        if (obj[key] > 0) {
            return Number(key);
        }
    }
    
    return -1;
};

console.log(findMissing(arr1, arr2));
8

How It Works

The algorithm uses a frequency counting approach:

  1. Count Phase: Create an object to count occurrences of each element in arr1
  2. Subtract Phase: Iterate through arr2 and decrement counts for each element found
  3. Find Missing: The element with remaining count > 0 is the missing number

Alternative Method Using Array Sum

For numeric arrays, we can use the mathematical difference between sums:

const findMissingBySum = (arr1, arr2) => {
    const sum1 = arr1.reduce((acc, num) => acc + num, 0);
    const sum2 = arr2.reduce((acc, num) => acc + num, 0);
    return sum1 - sum2;
};

const arr1 = [6, 1, 3, 6, 8, 2];
const arr2 = [3, 6, 6, 1, 2];

console.log(findMissingBySum(arr1, arr2));
8

Comparison of Methods

Method Time Complexity Space Complexity Works with Non-Numbers?
Frequency Counting O(n) O(n) Yes
Sum Difference O(n) O(1) No

Conclusion

The frequency counting method works universally for any data type, while the sum difference approach is more space-efficient for numeric arrays. Choose based on your specific requirements and data types.

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

659 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements