Largest Number At Least Twice of Others - Problem

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.

Input & Output

Example 1 — Valid Case
$ Input: nums = [3,6,1,0]
Output: 1
💡 Note: The largest element is 6 at index 1. It's at least twice every other element: 6 ≥ 2×3, 6 ≥ 2×1, 6 ≥ 2×0. So return index 1.
Example 2 — Invalid Case
$ Input: nums = [1,2,3,4]
Output: -1
💡 Note: The largest element is 4 at index 3. However, 4 < 2×3 = 6, so it's not at least twice the element 3. Return -1.
Example 3 — Edge Case
$ Input: nums = [1]
Output: 0
💡 Note: Single element array - the largest (and only) element is trivially at least twice every other element (there are none). Return index 0.

Constraints

  • 1 ≤ nums.length ≤ 50
  • 0 ≤ nums[i] ≤ 100
  • The largest element in nums is unique

Visualization

Tap to expand
Largest Number At Least Twice of Others INPUT Integer Array nums: 3 i=0 6 i=1 1 i=2 0 i=3 6 is the largest (highlighted) Input Values nums = [3, 6, 1, 0] length = 4 Check: Is 6 >= 2 * others? 6 >= 6, 6 >= 2, 6 >= 0 Second max = 3 6 >= 2*3 = 6 [OK] ALGORITHM STEPS 1 Initialize Trackers max = -INF, secondMax = -INF maxIndex = 0 2 Single Pass Scan Iterate through array once Track max and second max 3 Update Logic If num > max: secondMax = max, max = num Else if num > secondMax: secondMax = num 4 Final Check If max >= 2 * secondMax: return maxIndex Else: return -1 Final: max=6, secondMax=3 maxIndex=1 FINAL RESULT 3 6 1 0 Winner at index 1 OUTPUT 1 Verification max = 6 at index 1 secondMax = 3 6 >= 2 * 3 = 6 [OK] Condition satisfied! Key Insight: Instead of comparing the largest element with every other element (O(n) comparisons), we only need to track the second largest. If max >= 2 * secondMax, the condition is met for ALL elements. Time: O(n), Space: O(1) - Single pass with constant extra space. TutorialsPoint - Largest Number At Least Twice of Others | One Pass - Track Max and Second Max
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen