712213. Number of greater elements to the right

Medium

Number of Greater Elements to the Right

Summary

Given an array of distinct integers, we need to find the number of elements that are greater than each element in the array. This problem requires a thorough understanding of arrays and their manipulation.

Detailed Explanation

The approach to solving this problem is simple yet effective. We iterate through the array from right to left (i.e., from end to start) and maintain a count of greater elements for each element. For each iteration, we compare the current element with all the previous elements and increment the count whenever we find an element that is smaller than the current one.

Here's a step-by-step breakdown:

  1. Initialize a variable count to 0.
  2. Start from the rightmost element of the array (index n-1, where n is the size of the array).
  3. Compare the current element with all previous elements (n-2, n-3, ..., 0).
  4. For each comparison, increment count whenever you find an element that is smaller than the current one.
  5. Repeat steps 2-4 until you reach the first element of the array (index 0).
  6. The final value of count represents the number of greater elements to the right for each element in the array.

Time Complexity: O(n^2), where n is the size of the array. Space Complexity: O(1), as we only use a constant amount of space to store the count variable.

Optimized Solutions

Java

View on GeeksforGeeks
int[] arr = {4, 3, 7, 5};
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
    int count = 0;
    for (int j = i + 1; j < arr.length; j++) {
        if (arr[j] > arr[i]) {
            count++;
        }
    }
    result[i] = count;
}
for (int i : result) {
    System.out.println(i);
}

DevExCode

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

© 2026 DevExCode. All rights reserved.