Find the Third Maximum Number in an Array using JavaScript



In this article, we will learn to find the third maximum unique number in an array of JavaScript, or the largest number if there are fewer than three unique values. We will be using three methods: a single-pass approach for efficiency, a sorting method to identify the number after removing duplicates, and a combination of Set and Max-Heap for optimal handling of large datasets. Each method includes examples and a comparison of time and space complexities.

Problem Statement

Given an array of integers, find the third maximum unique number. If the array contains fewer than three unique numbers, return the largest number in the array.

Input

const nums = [7, 2, 5, 9, 9, 5, 3]; 
Output
The third maximum unique number is 5.

The time complexity of our function must not exceed O(n), we have to find the number in a single iteration.

Finding the third maximum number in an array

Following are the approaches to finding the third maximum number in an array ?

Using single-pass approach

Using the single-pass method, we iterate through the array while keeping track of the top three unique numbers ?

  • Initialize Variables: first, second, and third are set to -Infinity to handle any number in the array.
  • Update Maximums: Iterate through the array and update the maximum values accordingly.
  • Return the Result: Return the third maximum if found; otherwise, return the largest number.

Example

Below is the JavaScript program to find the third maximum number in an array ?

const arr = [1, 5, 23, 3, 676, 4, 35, 4, 2];
const findThirdMax = (arr) => {
  let [first, second, third] = [-Infinity, -Infinity, -Infinity];
  for (let el of arr) {
    if (el === first || el === second || el === third) {
      continue;
    }
    if (el > first) {
      [first, second, third] = [el, first, second];
      continue;
    }
    if (el > second) {
      [second, third] = [el, second];
      continue;
    }
    if (el > third) {
      third = el;
      continue;
    }
  }
  return third !== -Infinity ? third : first;
};
console.log(findThirdMax(arr));

Output

23

Using Sorting

Sorting is a straightforward way to find the third maximum number in an array. After sorting the array in descending order, we can access the third unique element directly.
Removing the duplicate elements in the array using the Set() method ?

const uniqueArr = [...new Set(arr)];

Sorting the array in descending order using the .sort() method ?

uniqueArr.sort((a, b) => b - a);

Example

Below is the JavaScript program to find the third maximum number in an array ?

function thirdMaxSort(arr) {
    // Remove duplicates using a Set
    const uniqueArr = [...new Set(arr)];
    
    // Sort the array in descending order
    uniqueArr.sort((a, b) => b - a);
    
    // Check if the array has at least three elements
    return uniqueArr.length >= 3 ? uniqueArr[2] : uniqueArr[0];
}

// Example usage
const nums = [3, 2, 1, 4, 4];
console.log(thirdMaxSort(nums)); 

Output

2

Using a Set and Priority Queue (Max-Heap)

Finding the third maximum unique number is done by utilizing a priority queue (max-heap) to keep track of the largest numbers. We can store the elements in a Set to eliminate duplicates, and then use a max-heap to efficiently retrieve the third largest number.

Following are the steps to find the third maximum number in an array ?

  • First, remove duplicates from the array using a Set.
  • Insert elements into a max-heap.
  • Pop the top three elements from the heap, which will represent the first, second, and third maximum numbers.

Example

Below is the JavaScript program to find the third maximum number in an array ?

class MaxHeap {
    constructor() {
        this.heap = [];
    }

    push(val) {
        this.heap.push(val);
        this._heapifyUp();
    }

    pop() {
        if (this.heap.length === 1) return this.heap.pop();
        const max = this.heap[0];
        this.heap[0] = this.heap.pop();
        this._heapifyDown();
        return max;
    }

    _heapifyUp() {
        let index = this.heap.length - 1;
        while (index > 0) {
            let parentIndex = Math.floor((index - 1) / 2);
            if (this.heap[parentIndex] >= this.heap[index]) break;
            [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]];
            index = parentIndex;
        }
    }

    _heapifyDown() {
        let index = 0;
        const length = this.heap.length;
        while (index < length) {
            let leftChild = 2 * index + 1;
            let rightChild = 2 * index + 2;
            let largest = index;

            if (leftChild < length && this.heap[leftChild] > this.heap[largest]) {
                largest = leftChild;
            }

            if (rightChild < length && this.heap[rightChild] > this.heap[largest]) {
                largest = rightChild;
            }

            if (largest === index) break;

            [this.heap[largest], this.heap[index]] = [this.heap[index], this.heap[largest]];
            index = largest;
        }
    }
}

function thirdMaxHeap(arr) {
    const uniqueSet = new Set(arr);
    const maxHeap = new MaxHeap();

    // Insert elements into the heap
    for (const num of uniqueSet) {
        maxHeap.push(num);
    }

    // Pop the first three elements
    let firstMax = maxHeap.pop();
    let secondMax = maxHeap.pop();
    let thirdMax = maxHeap.pop();

    // If there are fewer than 3 unique elements, return the largest one
    return thirdMax !== undefined ? thirdMax : firstMax;
}

// Example usage
const nums = [7, 2, 5, 9, 9, 5, 3];
console.log(thirdMaxHeap(nums));

Output

5

Comparison Table

Feature Single-Pass Approach  Sorting Approach Max-Heap Approach
Time Complexity O(n)  O(nlog?n) O(nlog?n)
Space Complexity O(1) O(n) O(n)
Use Case
Large datasets where efficiency matters Small to medium-sized arrays For scenarios where heap operations are necessary
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-13T21:50:14+05:30

816 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements