You are given an integer array nums
where the largest integer is at least twice as much as every other number in the array. If the largest integer is at least twice as much as every other number in the array, return the index of the largest integer, otherwise, return -1.
Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6
is the largest integer and for every other number in the array x
, 6 >= 2 * x
.
Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4
is the largest number, but 4 is not at least twice as much as every other number in the array.
Input: nums = [1]
Output: 0
Explanation: The largest number is 1
, and since there is no other number in the array, it meets the condition of being at least twice as much as every other number.
nums
always contain at least one element?
-1
.def dominantIndex(nums):
if not nums: # Check if the input array is empty
return -1
max_index = 0
max_value = nums[0]
# Find the largest number and its index
for i in range(1, len(nums)):
if nums[i] > max_value:
max_value = nums[i]
max_index = i
# Check if the largest number is at least twice as much as other numbers
for i in range(len(nums)):
if i != max_index and max_value < 2 * nums[i]:
return -1
return max_index
# Test cases to validate the solution
print(dominantIndex([3, 6, 1, 0])) # Output: 1
print(dominantIndex([1, 2, 3, 4])) # Output: -1
print(dominantIndex([1])) # Output: 0
print(dominantIndex([0, 0, 3, 2])) # Output: 2
O(n)
where n
is the number of elements in the nums
array.O(n)
.Overall, the time complexity of the solution is O(n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?