702868. At least two greater elements

Basic

At Least Two Greater Elements

Slug: at-least-two-greater-elements4625

Difficulty: Basic

Id: 702868

Topic Tags: Arrays, Sorting, Data Structures, Algorithms

Company Tags: Amazon

Summary

Given an array of integers, find if there are at least two elements that are greater than all the other elements in the array. The problem is about finding the maximum and second maximum values in the array.

Detailed Explanation

To solve this problem, we can sort the array in descending order. Then, we need to check if the first element is greater than all the other elements, which would mean it's the maximum value, and the second element (if it exists) should be greater than all the other elements except for the maximum one.

Here's a step-by-step breakdown of the solution:

  1. Sort the array in descending order.
  2. Check if the first element is greater than all the other elements.
  3. If yes, check if there are at least two elements that are greater than all the other elements (i.e., the first and second elements).

Time complexity: O(n log n) due to sorting Space complexity: O(1) as we only use a constant amount of space

Optimized Solutions

Java

View on GeeksforGeeks
public boolean hasAtLeastTwoGreaterElements(int[] arr) {
    Arrays.sort(arr);
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            return true;
        }
    }
    return false;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.