LeetCode 747: Largest Number At Least Twice of Others Solution

Master LeetCode problem 747 (Largest Number At Least Twice of Others), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

747. Largest Number At Least Twice of Others

Problem Explanation

Explanation

To solve this problem, we need to find the largest element in the array and check if it is at least twice as much as every other element. We can do this by iterating through the array and keeping track of the largest element and its index. Then, we iterate through the array again to verify if the largest element is at least twice as much as every other element. We return the index of the largest element if the condition is met, otherwise, we return -1.

  • Time complexity: O(n) where n is the number of elements in the array.
  • Space complexity: O(1)

Solution Code

class Solution {
    public int dominantIndex(int[] nums) {
        int maxIndex = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (i != maxIndex && nums[maxIndex] < 2 * nums[i]) {
                return -1;
            }
        }
        
        return maxIndex;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 747 (Largest Number At Least Twice of Others)?

This page provides optimized solutions for LeetCode problem 747 (Largest Number At Least Twice of Others) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 747 (Largest Number At Least Twice of Others)?

The time complexity for LeetCode 747 (Largest Number At Least Twice of Others) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 747 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 747 in Java, C++, or Python.

Back to LeetCode Solutions