Finding the third maximum number within an array in JavaScript

Finding the third maximum number in a JavaScript array requires handling duplicates and edge cases where fewer than three unique values exist.

The task is to return the third largest unique number from an array. If fewer than three unique numbers exist, return the maximum number instead.

Problem Example

For the input array:

[34, 67, 31, 87, 12, 30, 22]

The unique numbers sorted in descending order are: [87, 67, 34, 31, 30, 22, 12]

The third maximum is 34.

Solution Approach

The algorithm works by:

  1. Removing duplicates using a hash map
  2. Checking if we have at least 3 unique numbers
  3. If yes, sorting and returning the third largest
  4. If no, returning the maximum number

Complete Implementation

const arr = [34, 67, 31, 87, 12, 30, 22];

const findThirdMax = (arr = []) => {
    const map = {};
    let j = 0;
    
    // Remove duplicates
    for (let i = 0, l = arr.length; i < l; i++) {
        if (!map[arr[i]]) {
            map[arr[i]] = true;
        } else {
            continue;
        }
        arr[j++] = arr[i];
    }
    
    arr.length = j;
    let result = -Infinity;
    
    if (j < 3) {
        // Less than 3 unique numbers, return maximum
        for (let i = 0; i < j; ++i) {
            result = Math.max(result, arr[i]);
        }
        return result;
    } else {
        // Sort in descending order and return third element
        arr.sort(function (prev, next) {
            if (next >= prev) return -1;
            return 1;
        });
        return arr[2]; // Third element (index 2)
    }
};

console.log("Input:", [34, 67, 31, 87, 12, 30, 22]);
console.log("Third maximum:", findThirdMax(arr));
Input: [34, 67, 31, 87, 12, 30, 22]
Third maximum: 34

Alternative Approach Using Set

A cleaner solution using JavaScript's Set for duplicate removal:

const findThirdMaxSimple = (arr) => {
    // Remove duplicates and sort in descending order
    const uniqueNums = [...new Set(arr)].sort((a, b) => b - a);
    
    // Return third max if exists, otherwise return max
    return uniqueNums.length >= 3 ? uniqueNums[2] : uniqueNums[0];
};

// Test with different arrays
console.log("Array [3, 2, 1]:", findThirdMaxSimple([3, 2, 1])); // 1
console.log("Array [1, 2]:", findThirdMaxSimple([1, 2])); // 2 (max)
console.log("Array [2, 2, 3, 1]:", findThirdMaxSimple([2, 2, 3, 1])); // 1
Array [3, 2, 1]: 1
Array [1, 2]: 2
Array [2, 2, 3, 1]: 1

Edge Cases

The function handles several important edge cases:

  • Duplicates: [2, 2, 3, 1] ? third max is 1
  • Less than 3 unique: [1, 2] ? returns max (2)
  • All same: [5, 5, 5] ? returns 5
  • Negative numbers: [-1, -2, -3] ? returns -3

Comparison of Approaches

Method Time Complexity Space Complexity Readability
Hash Map + Sort O(n log n) O(n) Complex
Set + Sort O(n log n) O(n) Simple

Conclusion

Both approaches solve the third maximum problem effectively. The Set-based solution is more readable and concise, while the hash map approach offers more control over the deduplication process.

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

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements