Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Superior Elements

Easy
0/40
Average time to solve is 30m
profile
Contributed by
231 upvotes

Problem statement

There is an integer array ‘a’ of size ‘n’.


An element is called a Superior Element if it is greater than all the elements present to its right.


You must return an array all Superior Elements in the array ‘a’.


Note:

The last element of the array is always a Superior Element. 


Example

Input: a = [1, 2, 3, 2], n = 4

Output: 2 3

Explanation: 
a[ 2 ] = 3 is greater than a[ 3 ]. Hence it is a Superior Element. 
a[ 3 ] = 2 is the last element. Hence it is a Superior Element.
The final answer is in sorted order.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer, ‘n’.
The second line has ‘n’ integers denoting the array ‘a’.


Output Format:
You must return an array with all Superior elements.


Note:
You don’t need to print anything. Just implement the given function. Final answer will be printed in a sorted order.
Sample Input 1:
4 
1 2 2 1


Sample Output 1:
1 2


Explanation of Sample Input 1:
Element present at the last index is '1' and is a superior element since there are no integers to the right of it.
Element present at index 2 (0-indexed) is '2' and is greater than all the elements to the right of it.
There are no other superior elements present in the array.
Hence the final answer is [1,2].


Sample Input 2:
3
5 4 3


Sample Output 2:
3 4 5 


Expected Time Complexity:
Try to solve this in O(n).


Constraints:
1 <= n <=10^5 
1 <= a[i] <= 10^9
Time Limit: 1 sec
Hint

Simulate the problem statement. 

Approaches (2)
Brute Force

Approach:

 

  • We can use two loops to solve the problem.
  • The outer loop goes from 0 to ‘N’- 1, picking each element from left to right.
  • The inner loop compares the selected element to every element on its right side.
  • The chosen element is Superior if it is larger than all elements to its right.

Algorithm:

 

Function int superiorNumber([int] A):

  1. Initialize an empty array, ‘answer’.
  2. For ‘i’ from ‘N’-1 to 0:
    • Initialize the boolean variable ‘flag’ with true.
    • For ‘j’ from ‘i’ + 1 to ‘N’-1:
      • If A[ j ] >= A[ i ]:
        • ‘Flag’ = false
    • If flag == true:
      • Push A[ i ] to ‘answer’ array.
  3. Sort the array ‘answer’
  4. Return ‘answer’.
Time Complexity

O( N^2 ), Where ‘N’ is given input. 

 

We are using two loops. Outer is used to iterate on each element of the array, and the inner loop is used to iterate on the elements on its right. Also, we take N * log( N ) time for sorting the array. Hence, the overall time complexity will be O( N^2 ).

Space Complexity

O( 1 ). 

 

We are taking O( 1 ) extra space for the variables. Hence, the overall space complexity will be O( 1 ).

Code Solution
(100% EXP penalty)
Superior Elements
All tags
Sort by
Search icon

Interview problems

JAVA || Iterate from right to left ans store the max element.

import java.util.*;

public class Solution {

    public static List< Integer > superiorElements(int []a) {

        // Write your code here.

        // itterate from right to left ans store the max element.

 

        ArrayList<Integer> list = new ArrayList<>();

        list.add(a[a.length-1]);

        for (int i=a.length-2; i>=0; i--) {

            if (a[i] > list.get(list.size()-1)) {

                list.add(a[i]);

            }

        }

 

        return list;

    }

}

27 views
0 replies
0 upvotes

Interview problems

SIMPLE BACKTRAVERSAL SOLUTION || O(n) TIME COMPLEXITY

vector<int> superiorElements(vector<int>&a) {

    vector<int> ans;

    int max = INT_MIN;

    for(int i = a.size() - 1; i >=0; i--){

        if(a[i] > max){

            max = a[i];

            ans.push_back(max);

        }

    }

    return ans;

}

beginners

65 views
0 replies
0 upvotes

Interview problems

✨ Finding Superior Elements in an Array: An Optimal Approach 🚀

To solve this problem efficiently, we will iterate over the array from right to left and keep track of the maximum element found so far. This is because the "superior elements" are those that are greater than all elements to their right, and by traversing from the end, we can easily keep track of the maximum element seen.

Step-by-Step Approach:

 

  1. Initialize Variables:
  • Start by finding the length of the array, size.
  • Create a variable max to keep track of the maximum element seen so far, initializing it to the last element of the array.
  • Create a list arr to store the superior elements found.

    2. Add the Last Element:

  • The last element of the array is always a superior element (since no elements are to its right), so add a[size - 1] to the list arr.

   3. Traverse the Array Backwards:

  • Iterate from the second-to-last element (size - 2) down to the first element (0).
  • For each element, compare it with the current maximum (max):
    • If the current element is greater than max, it is a superior element. Add it to the list arr and update max.

   4. Return the Result:

  • Since we collected elements from right to left, the superior elements are stored in reverse order. We can return the list as is if the order is not a concern, or reverse it before returning if needed.

 

 

 

 

Example Trace

 

Let's take the input array a = {2, 7, 5, 3, 6, 4, 8, 1} and trace the solution:

 

Initialization:

  • size = 8
  • max = a[7] = 1
  • arr = [1] (since the last element 1 is always a superior element)

Iterate from Right to Left:

  • i = 6: a[6] = 8 > max = 1 → Add 8 to arr, update max = 8 → arr = [1, 8]
  • i = 5: a[5] = 4 < max = 8 → Skip
  • i = 4: a[4] = 6 < max = 8 → Skip
  • i = 3: a[3] = 3 < max = 8 → Skip
  • i = 2: a[2] = 5 < max = 8 → Skip
  • i = 1: a[1] = 7 < max = 8 → Skip
  • i = 0: a[0] = 2 < max = 8 → Skip

Result:

  • arr = [1, 8] (Correct set of superior elements)
Time Complexity
  • The solution runs in O(n) time complexity, where n is the size of the array. This is because we only make a single pass through the array from right to left.
  • The space complexity is O(1) if we don't consider the output list; otherwise, it's O(k) where k is the number of superior elements.
32 views
0 replies
0 upvotes

Interview problems

C++ optimal solution

vector<int> superiorElements(vector<int>&a) {

    // Write your code here.

    vector<int> ans;

    int maxi=INT_MIN;

    int n=a.size();

    for(int i=n-1;i>=0;i--)

    {

        if(a[i]>maxi)

        {

            ans.push_back(a[i]);

        }

        maxi=max(maxi,a[i]);

    }

    return ans;

}

54 views
0 replies
0 upvotes

Interview problems

Simplest O(N) solution in Java

import java.util.*;
public class Solution {
    public static List< Integer > superiorElements(int []a) {
        // Write your code here.
        List<Integer>arr=new ArrayList<Integer>();
        int max=a[a.length-1];
        arr.add(max);
        for(int i=a.length-2;i>=0;i--)
        {
            if(a[i]>max)
            {
                max=a[i];
                arr.add(max);
            }
        }
        return arr;
    }
}

java

94 views
0 replies
0 upvotes

Interview problems

Easy and Simple C++ Solution

vector<int> superiorElements(vector<int>&a) {

    // Write your code here.

    vector<int> ans;

    int maxi = INT_MIN;

    int n = a.size();

    for(int i = n-1;i>=0;i--){

        if(a[i]>maxi){

            ans.push_back(a[i]);

        }

        maxi = max(maxi, a[i]);

    }

    sort(ans.begin(),ans.end());

    return ans;

}

113 views
0 replies
3 upvotes

Interview problems

This is the Unique Optimal Solution where great programmers don't know.

vector<int> superiorElements(vector<int>&a) {

    int i=0;

    int n=a.size();

    while(i<n-1){

        if(a[i]<=a[i+1]){

            a.erase(a.begin()+i);

            n=a.size();

            if(i>0) i--;

        }

        else i++;

    }

    reverse(a.begin(),a.end());

    return a;

}

69 views
0 replies
0 upvotes

Interview problems

Optimal Solution of Superior Element problem in C++

vector<int> superiorElements(vector<int>&a) {
    vector<int> ans;
    int n = a.size();
    int maxi = INT_MIN;

    for(int i=n-1; i>=0; i--){
        if(a[i] > maxi){
            ans.push_back(a[i]);
        }
        maxi = max(maxi, a[i]);
    }
    return ans;
}
// Time complexity: o(n) for identifying the leader ( line 6 - 11)
// space complexity: o(n) for returning the answer 
 
127 views
0 replies
0 upvotes

Interview problems

Solution for finding Superior Elements

An element is called a Superior Element if it is greater than all the elements present to its right. import java.util.*;

public class Solution {

    public static List< Integer > superiorElements(int []a) {

        

        ArrayList<Integer> ans = new ArrayList<>();

        int n = a.length;

 

        int maximum= -1;

        for(int i=n-1; i>=0; i--){

            if(a[i] > maximum){

                // If value of element is greter than max

                // max value will be replaced with bigger element

                // element will be added to list

                maximum = a[i];

                ans.add(a[i]);

            }

        }

        return ans;  

    }

}

77 views
0 replies
1 upvote

Interview problems

C++ Most Efficient & Easy solution in O(n)

vector<int> superiorElements(vector<int>&a) {
    vector<int> ans;
    int n = a.size();
    int max = a[n-1];


    ans.push_back(a[n-1]);


    for(int i=n-2; i>=0; i--){
        if(a[i] > max){
            max = a[i];
            ans.push_back(a[i]);
        }
    }
    return ans;
}
91 views
0 replies
1 upvote
Full screen
Console