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:
- 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.