DEV Community

Mridu Bhatnagar
Mridu Bhatnagar

Posted on

1

Day-12 Largest number at least twice of others

This problem statement is a part of Leetcode's card Arrays and Strings under the sub-heading Introduction to Arrays.

Problem Statement

In a given integer array nums, there is always exactly one largest element.

Find whether the largest element in the array is at least twice as much as every other number in the array.

If it is, return the index of the largest element, otherwise, return -1.

Example 1
Input: nums = [3, 6, 1, 0]
Output: 1
Explanation: 6 is the largest integer and for every other number in the array x,
6 is more than twice as big as x.  The index of value 6 is 1, so we return 1.
Example 2
Input: nums = [1, 2, 3, 4]
Output: -1
Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.

Note:

  1. nums will have a length in the range [1, 50].
  2. Every nums[i] will be an integer in the range [0, 99].
Solution Approach
  1. Find the largest element and index of the largest element from the array.
  2. Iterate over the array and check if twice the value of all other elements is less than the largest_element. If this condition is False return -1 else return the index of the largest element.
class Solution:
    def dominantIndex(self, nums: List[int]) -> int:
        largest_element = max(nums)
        result = nums.index(largest_element)
        for index, value in enumerate(nums):
            if (value != largest_element) and (largest_element < 2*value):
                result = -1

        return result
Learnings
  1. Time complexity of the solution is 0(n)
  2. Space complexity is 0(1)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay