Skip to main content

Largest Number At Least Twice of Others

Problem Description​

You are given an integer array nums where the largest integer is unique.

Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.

Example​

Example 1:

Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least twice as big as x.
The index of value 6 is 1, so we return 1.

Example 2:

Input: nums = [1,2,3,4]
Output: -1
Explanation: 4 is less than twice the value of 3, so we return -1.

Constraints​

  • 0 <= nums[i] <= 100

Solution Approach​

Intuition:​

To efficiently determine Largest Number At Least Twice of Others

Solution Implementation​

Code In Different Languages:​

Written by @Ishitamukherjee2004
 
class Solution {
dominantIndex(nums) {
let cnt = 0, index = -1;
let maxi = -Infinity, smax = -Infinity;
for(let i = 0; i < nums.length; i++){
if(nums[i] >= maxi){
smax = maxi;
maxi = nums[i];
index = i;
} else if(nums[i] < maxi && nums[i] >= smax){
smax = nums[i];
}
}
if(maxi >= 2 * smax) return index;
return -1;
}
}





Complexity Analysis​

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1)
  • The time complexity is O(n)O(n) where n is the length of the input array nums. This is because the algorithm iterates through the array once, performing a constant amount of work for each element.
  • The space complexity is O(1)O(1) because we are not using any extra space.