Click here to see the problem in LeetCode. And read the problem’s details.
This one is a pretty simple problem. We will be given an integer array. We have to find the largest element’s index, which is must be at least twice as much as every other number in the array.
If it’s not matched with the condition, we have to return -1.
There are many ways to solve this problem.
To solve this problem, first, we will find the largest number from the given array. To do that, we will use a built-in Python function called max and store it in a variable (m). Again in another variable (index), we will store its index.
After that, we will run a loop to visit all the elements of the given array. Inside the loop, we will check something. Which is, the maximum number is less than or not the current (number * 2). If it is less, that means it does not meet the criteria of this problem. Then we can easily send back (return) -1. But one more thing to check, which is; the current position can not be the maximum number’s index.
If the loop successfully finished and didn’t go into the loop’s ‘if’ block, we can say that the largest element in the array is at least twice as much as every other number in the array. And after the loop, we will return the maximum number position, which is in the index variable.
Let’s see the solution. It will help you more to understand.
class Solution: def dominantIndex(self, nums: List[int]) -> int: m = max(nums) index = nums.index(m) for i in range(len(nums)): if m < nums[i] * 2 and i != index: return -1 return index
I hope you got the idea. Try to understand the solution with a simple example first.
Happy Learning 🙂
Happy Coding 🙂