algorithm
data-structures
array
coding-problems
competitive-programming

Find next higher element in an array for each element

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Here's a detailed article on finding the next higher element in an array for each element:


Introduction

In the problem of finding the next higher or greater element for each element of an array, the goal is to identify the first element that is greater than the current element for each position within the array. This is a common problem encountered in various computational scenarios, such as stock price analysis, data processing pipelines, and algorithm optimizations. The efficiency of solving this problem can have a significant impact on performance, particularly for large datasets.

Problem Statement

Given an array of integers, arr[], for each element arr[i], find the smallest index j such that:

  • j > i
  • arr[j] > arr[i]

If no such j exists, the next higher element for arr[i] should be marked as -1.

Approaches

Naive Approach

The straightforward way to solve this problem is to use a nested loop structure:

  1. For each element in the array, iterate through the subsequent elements.
  2. Compare and find the first element that is greater than the current element.

This approach has a time complexity of O(n2)O(n^2), where nn is the number of elements in the array. This is due to the nested iteration over all pairs, making it inefficient for large arrays.

python
1def find_next_higher_naive(arr):
2    n = len(arr)
3    result = [-1] * n
4    for i in range(n):
5        for j in range(i + 1, n):
6            if arr[j] > arr[i]:
7                result[i] = arr[j]
8                break
9    return result

Efficient Approach Using a Stack

A more efficient approach leverages a stack data structure to maintain a list of elements whose next higher element hasn't been found yet. The time complexity of this approach is O(n)O(n), as each element is pushed and popped from the stack only once.

Algorithm:

  1. Initialize an empty stack and a result list filled with -1.
  2. Traverse the array from right to left (i.e., reverse order):
    • While the stack is not empty and the top of the stack is less than or equal to the current element, pop the stack.
    • If the stack is not empty after the pop operations, the top of the stack is the next higher element for the current element.
    • Push the current element onto the stack.
  3. The result list will contain the next higher elements for each position in the original array.
python
1def find_next_higher_efficient(arr):
2    n = len(arr)
3    result = [-1] * n
4    stack = []
5
6    for i in range(n - 1, -1, -1):
7        while stack and stack[-1] <= arr[i]:
8            stack.pop()
9
10        if stack:
11            result[i] = stack[-1]
12
13        stack.append(arr[i])
14
15    return result

Example

Let's consider an example array to illustrate both approaches:

python
arr = [4, 5, 2, 25, 7, 8]

For the naive approach, the result would be:

  • For 4, the next higher is 5.
  • For 5, the next higher is 25.
  • For 2, the next higher is 25.
  • For 25, there is no higher element, so -1.
  • For 7, the next higher is 8.
  • For 8, there is no higher element, so -1.

Result: [5, 25, 25, -1, 8, -1]

Using the efficient stack-based approach, we'll get the same result faster.

Summary Table

ElementNext Higher Element
45
525
225
25-1
78
8-1

Additional Details

Stack-Based Solution Advantages

  • Time Complexity: The time complexity is O(n)O(n), which makes it suitable for large datasets.
  • Space Complexity: Since we use a stack to store elements, the space complexity is O(n)O(n) in the worst case, which is manageable.

Applications

  • Stock Span Problem: Can be adapted to determine the span of stock’s price for all days.
  • Temperature Monitoring: Find the next hottest day for a sequence of daily temperatures.
  • Data Streaming: Efficient online computation for finding peaks in streaming data.

In conclusion, the stack-based solution offers an efficient way to solve the problem, ensuring that large datasets can be processed quickly while maintaining clarity in implementation.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.