Given a list of integers (
nums), return whether the largest number is bigger than the second-largest number by more than two times.
2 ≤ n ≤ 100,000 where
nis the length of
nums = [3, 6, 9]
9 is not bigger than 2 * 6
Python has a neat, built-in function called
sorted(list_paremeter) that returns the passed list in sorted order.
Let’s assume that there’s a list:
L = [ 15, 23, 6, 2, 7 ].
Now, if we have to sort the list in descending order we would get:
L = [ 23, 15, 7, 6, 2].
Here, we can observe that the first element is the largest element and that it is followed by the second largest element. Therefore, by comparing these two elements would directly get our answer.
To get the passed list in descending order, we would have to pass another argument (
reverse = True) that tells the function to return the list in descending order. Since the returned value is a list, we can directly call the 0-th element and 1-th element with
sorted(nums, reverse=True) and
sorted(nums, reverse=True) respectively.
As the problem states, the first element must be bigger than twice the second largest element, so we multiply 2 to the 1-th element.
Then, in order to compare the values we will use the
> operator, which returns
False based on the passed values.
Let’s assume that
nums = [ 1, 4, 2, 7, 3].
sorted(nums, reverse=True) returns the value of
(sorted(nums, reverse=True) * 2) returns the value of
Then, the program checks if
7 > 8. Since it is not, it returns
def larg_check( nums): return sorted(nums,reverse = True) > (sorted(nums,reverse = True)*2) nums = [3,4,2,6,7,1,5] print(larg_check(nums))
sorted() method uses TimSort whose average time complexity is O(N log N).
The program uses a list of
n elements that each take O(1). So for
n elements, it takes O(n).
View all Courses