You get a list of whole numbers, nums, whose largest value appears only once.
Check whether that largest number is at least twice as big as every other number in the list. If it is, return its index. If not, return −1.
Example 1
Input: nums = [2, 9, 4, 1] Output: 1 Why: 9 is at least double 2, 4 and 1
2 more examples and the constraints
Example 2
Input: nums = [5, 7, 4] Output: -1 Why: double 5 is 10, more than 7
Example 3
Input: nums = [0, 3] Output: 1 Why: 3 is at least double 0
Constraints
- 2 ≤ length of nums ≤ 50
- 0 ≤ nums[i] ≤ 100
- The largest value appears exactly once
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Find the max, then checkO(n)
- Track the top twoO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50 numbers | Verdict |
|---|---|---|---|
| Find the max, then check | O(n) | Clear; two passes | |
| Track the top two | O(n) | Best; one pass |
n = length of nums.
Edge cases to test
- Exactly double. [3, 6] gives 1: at least twice includes equal.
- Zeros. [0, 3] gives 1, since 2 × 0 = 0.
- Largest comes first. [100, 50, 49] gives 0; do not assume the largest is late.
- Just short. [100, 51] gives −1: 2 × 51 = 102 is above 100.
- Two numbers only. The second largest is simply the other number.
Common mistakes
- Comparing the largest with itself, so 2 × largest > largest always gives −1.
- Using
>instead of>=, which fails the exactly-double case. - Forgetting to move the old largest down to second when a bigger number arrives.
How to talk through it
- 1Clarify. Is the largest unique? Does exactly double count? Are values ever negative?
- 2Give the direct check. Find the max, then check every other number doubled: two passes.
- 3Reduce the check. Only the second largest can break the rule, so track the top two.
- 4Code the one pass. On a new largest, shift the old one to second; else maybe update second.
- 5Test out loud. Run the exactly-double and largest-first cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?