Algorithm

Elusive Least Occurring Number in an Array

Given an array of integers, find the number that appears the fewest times. If there's a tie, return any of them.

6 May 2024

Elusive Least Occurring Number in an Array

Given an array of integers, find the number that appears the fewest times. If there's a tie, return any of them.

This comes up in anomaly detection, log analysis, and anywhere you need to find the outlier in a frequency distribution.

The intuition

Two passes. First, count how often each number appears. Second, find the one with the smallest count. A Map handles the counting cleanly.

Javascript
const solution = (numbers) => {
    const counts = new Map();

    for (const num of numbers) {
        counts.set(num, (counts.get(num) || 0) + 1);
    }

    let leastNum = numbers[0];
    let leastCount = Infinity;

    for (const [num, count] of counts) {
        if (count < leastCount) {
            leastCount = count;
            leastNum = num;
        }
    }

    return leastNum;
};

Complexity

  • Time: O(n) — one pass to count, one pass over unique values.
  • Space: O(k) where k is the number of distinct values.

A real-world example

I used this pattern once to find misconfigured servers. We logged health checks and the server that reported the fewest "healthy" pings was the one silently failing. Same algorithm — count occurrences, find the minimum.

The approach scales well. Even with millions of entries, you're doing two linear passes and a map lookup. The bottleneck is usually I/O, not the counting.

Keep reading