Largest Number At Least Twice of Others — LeetCode 747 Python Solution
EasyArraySorting
- Problem
- #747
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [3,6,1,0]
- Output
- 1
- Explanation
- 6 is the largest integer.
Python solution
Python
class Solution:
def dominantIndex(self, nums: List[int]) -> int:
x, y = nlargest(2, nums)
return nums.index(x) if x >= 2 * y else -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array nums |
| Space | O(1) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 747. Largest Number At Least Twice of Others is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 747. Largest Number At Least Twice of Others?
- LeetCode 747. Largest Number At Least Twice of Others is rated Easy on LeetCode.
- What is the time complexity of LeetCode 747. Largest Number At Least Twice of Others?
- The Python solution on this page runs in O(n), where n is the length of the array nums.
- What is the space complexity of LeetCode 747. Largest Number At Least Twice of Others?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 747. Largest Number At Least Twice of Others cover?
- LeetCode 747. Largest Number At Least Twice of Others is tagged Array and Sorting on LeetCode.