Largest Number At Least Twice of Others in Python

Given an integer array nums, we need to check whether the largest element is at least twice as large as every other number in the array. If it satisfies this condition, return the index of the largest element, otherwise return -1.

So, if the input is like [3, 6, 1, 0], then the output will be 1, as 6 is the largest number, and for every other number in the array x, 6 is more than twice as big as x. Since the index of 6 is 1, the output is 1.

Algorithm

To solve this problem, we will follow these steps ?

  • Find the maximum value in the array
  • Iterate through the array to:
    • Store the index of the maximum element
    • Check if maximum < 2 * (other elements). If so, return -1
  • If all conditions are satisfied, return the maximum element's index

Example

class Solution:
    def dominantIndex(self, nums):
        maximum = max(nums)
        maxindex = 0
        
        for i in range(len(nums)):
            if nums[i] == maximum:
                maxindex = i
            elif maximum < 2 * nums[i]:
                return -1
        
        return maxindex

# Test the solution
ob = Solution()
result = ob.dominantIndex([3, 6, 1, 0])
print("Input:", [3, 6, 1, 0])
print("Output:", result)
Input: [3, 6, 1, 0]
Output: 1

How It Works

Let's trace through the example [3, 6, 1, 0] ?

  • Maximum element is 6
  • Check each element:
    • 3: Is 6 ? 2 * 3? Yes (6 ? 6) ?
    • 6: This is the maximum, store index 1
    • 1: Is 6 ? 2 * 1? Yes (6 ? 2) ?
    • 0: Is 6 ? 2 * 0? Yes (6 ? 0) ?
  • Return index 1

Additional Examples

class Solution:
    def dominantIndex(self, nums):
        maximum = max(nums)
        maxindex = 0
        
        for i in range(len(nums)):
            if nums[i] == maximum:
                maxindex = i
            elif maximum < 2 * nums[i]:
                return -1
        
        return maxindex

# Test with different cases
ob = Solution()

# Case 1: Dominant element exists
print("Test 1:", ob.dominantIndex([3, 6, 1, 0]))  # Output: 1

# Case 2: No dominant element
print("Test 2:", ob.dominantIndex([1, 2, 3, 4]))  # Output: -1

# Case 3: Single element
print("Test 3:", ob.dominantIndex([5]))  # Output: 0
Test 1: 1
Test 2: -1
Test 3: 0

Conclusion

This algorithm efficiently finds whether the largest element is at least twice as large as all other elements in O(n) time complexity. The key insight is to iterate once through the array, comparing the maximum with twice the value of each other element.

Updated on: 2026-03-25T08:49:25+05:30

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements