How to Find the Largest Unique Number in Array using Javascript (Functional Programming)


JS How to Find the Largest Unique Number in Array using Javascript (Functional Programming) algorithms javascript math

NodeJs / Javascript

Given an array of integers A, return the largest integer that only occurs once. If no integer occurs once, return -1.

Example 1:
Input: [5,7,3,9,4,9,8,3,1]
Output: 8
Explanation:
The maximum integer in the array is 9 but it is repeated. The number 8 occurs only once, so it’s the answer.

Example 2:
Input: [9,9,8,8]
Output: -1

Explanation:
There is no number that occurs only once.

Note:
1 <= A.length <= 2000
0 <= A[i] <= 1000

There are many algorithms to find the largest unique number in an array. And the functional programming often is one of the most elegant soluitons – which is concise.

To find the largest unique number, we can first use the Array.prototype.filter() in Javascript, to filter out the duplicate numbers. One easy filtering condition would be to check the first and last index that the element occurs in the array, using the indexOf and lastIndexOf respectively. If both indices are the same, the number is unique. However, this approach runs at O(N^2) as the indexOf and lastIndex takes O(N) worst comparisons and there are N items in the array.

However, the approach uses O(1) constant, compared to the traditional approach of using a hash map to record the item frequency. Once the unique numbers are stored in the array, we can use the Math.max(…arr) – triple dots operator to expand the array and return the maximum value.

However, the unique numbers may be empty, in this case the following produces -Infinity.

1
Math.max(...[])
Math.max(...[])

In this case, we can use the Javascript‘s isFinite function to test if the result is a finite number e.g. integers, floating numbers.

1
2
3
4
5
6
7
8
/**
 * @param {number[]} A
 * @return {number}
 */
var largestUniqueNumber = function(A) {
    const num = Math.max(...A.filter(a => A.indexOf(a) === A.lastIndexOf(a)));
    return isFinite(num) ? num : -1;
};
/**
 * @param {number[]} A
 * @return {number}
 */
var largestUniqueNumber = function(A) {
    const num = Math.max(...A.filter(a => A.indexOf(a) === A.lastIndexOf(a)));
    return isFinite(num) ? num : -1;
};

The C++ solutions are here: How to Find the Largest Unique Number in Array? and Similarly: Python Method to Find the Largest Unique Number in an Array

Largest Unique Numbers Algorithms/Implementations

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
606 words
Last Post: The Git Pre-Commit Hook to Avoid Pushing Only Unit Tests In NodeJs
Next Post: Python Method to Find the Largest Unique Number in an Array

The Permanent URL is: How to Find the Largest Unique Number in Array using Javascript (Functional Programming)

Leave a Reply