#747
Largest Number At Least Twice of Others
EasyArraySortingArraySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution improves efficiency by combining the two scans into one. We find the maximum and check the condition in a single pass, reducing the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize variables to track the maximum value, its index, and a flag for the condition check.
- 2Step 2: Loop through the array once to find the maximum value and check if it is at least twice as large as every other number.
- 3Step 3: If the condition fails for any number, return -1. If it passes for all, return the index of the maximum value.
solution.py14 lines
1# Full working Python code
2nums = [3, 6, 1, 0]
3max_value = nums[0]
4max_index = 0
5for i in range(1, len(nums)):
6 if nums[i] > max_value:
7 max_value = nums[i]
8 max_index = i
9for num in nums:
10 if num != max_value and max_value < 2 * num:
11 print(-1)
12 break
13else:
14 print(max_index)ℹ
Complexity note: The time complexity is O(n) because we only loop through the array once. The space complexity is O(1) since we use a constant amount of extra space.
- 1The largest element is guaranteed to be unique, simplifying the problem.
- 2We can combine finding the maximum and checking the condition in one pass for efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.