Taro Logo

Next Greater Element II

#208 Most AskedMedium
Topics:
ArraysStacks

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

Example 1:

Input: nums = [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number. 
The second 1's next greater number needs to search circularly, which is also 2.

Example 2:

Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]

Constraints:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How large can the input array be, and should I expect memory constraints with the output?
  2. Can the input array be empty, and what should be returned in that case?
  3. Are duplicate values allowed in the array, and how should we handle them when searching for the next greater element?
  4. Should the result contain the actual values of the next greater elements or their indices?
  5. Since the array is circular, does the search for a greater element wrap around past the end of the array to the beginning, and can an element be considered its own next greater element if it loops back to itself?

Brute Force Solution

Approach

Imagine you are holding a circular list of numbers and need to find the very next number that is larger than the one you are currently looking at, wrapping around to the beginning if necessary. The brute force approach exhaustively checks the numbers that follow each item one by one until a larger number is found.

Here's how the algorithm would work step-by-step:

  1. Pick the first number in the circular list as your starting point.
  2. Look at the numbers immediately following it in order, continuing past the end and back to the beginning if you reach the end of the list.
  3. Keep looking at these subsequent numbers one by one until you spot the first number that is strictly larger than your starting number.
  4. If you find a larger number, make a note of it and stop searching for the current starting point.
  5. If you look all the way around the entire circular list and still do not find any number larger than your starting point, make a note that no such number exists.
  6. Move on to the next number in the list and repeat the entire search process from the beginning.
  7. Continue this exhaustive checking process for every single number in the list until every starting point has its corresponding result recorded.

Code Implementation

def next_greater_elements(numbers_list):
    total_elements = len(numbers_list)
    result_array = [-1] * total_elements

    # Iterate through every element to find its next greater element in a circular manner
    for current_index in range(total_elements):
        found_greater = False
        
        for offset in range(1, total_elements):
            next_index = (current_index + offset) % total_elements
            
            # Check subsequent elements one by one, wrapping around the circular list
            if numbers_list[next_index] > numbers_list[current_index]:
                result_array[current_index] = numbers_list[next_index]
                found_greater = True
                break

    # Return the final results containing the next greater elements for each position
    return result_array

Big(O) Analysis

Time Complexity
O(n²) – Because the array is circular, the brute force approach requires us to potentially examine nearly all n elements for every single one of the n starting numbers in the list. For the first element, we might check up to n minus 1 subsequent elements, and we repeat this exhaustive search process independently for each item. This means we perform nested scanning operations across n elements for a total of n times. Summing these checks yields approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(N) – To solve the circular Next Greater Element problem efficiently, we utilize an auxiliary monotonic stack to store indices of the array elements, along with an output array of size N to record the results. In the worst-case scenario, such as a strictly decreasing sequence, the stack will store up to N indices simultaneously during our simulated two-pass traversal. Therefore, the extra memory required grows linearly with the input size N, resulting in an auxiliary space complexity of O(N).

Optimal Solution

Approach

To find the next greater value efficiently in a circular arrangement, we can use a mental waiting line to keep track of numbers that are still looking for something bigger. By walking through the sequence twice to account for the circular nature, we can instantly match numbers with their next greater partner the moment we find it.

Here's how the algorithm would work step-by-step:

  1. Imagine you are walking down a line of people holding numbers, and because the line is a loop, you need to walk past everyone twice to check all possible circular connections.
  2. Carry a notepad of people who are still waiting to find someone taller or greater than themselves.
  3. As you look at each person, check if their number is greater than the numbers of the people waiting on your notepad.
  4. If your current person is greater, they successfully answer the search for those waiting people, so you cross those people off your notepad.
  5. Then, add your current person to the notepad so they can start waiting for their own greater number to appear.
  6. Continue this process all the way through the second pass of the circular line.
  7. Anyone left on your notepad at the very end never found a greater number, so assign them a placeholder indicating no greater value exists.

Code Implementation

def next_greater_elements(input_numbers):
    sequence_length = len(input_numbers)
    result_array = [-1] * sequence_length
    waiting_notepad = []

    # Traverse twice to simulate the circular loop and check all wrap-around connections.
    for traversal_index in range(sequence_length * 2):
        current_index = traversal_index % sequence_length
        current_value = input_numbers[current_index]

        # Resolve waiting elements whenever a newly encountered value is strictly greater.
        while waiting_notepad and input_numbers[waiting_notepad[-1]] < current_value:
            resolved_index = waiting_notepad.pop()
            result_array[resolved_index] = current_value

        # Only record indices during the first pass to avoid redundant duplicate entries.
        if traversal_index < sequence_length:
            waiting_notepad.append(current_index)

    return result_array

Big(O) Analysis

Time Complexity
O(n) – To handle the circular array, we iterate through the sequence of size n exactly twice, resulting in 2n total steps. During these passes, every element is pushed onto and popped from the waiting line stack at most once. Because each element undergoes these stack operations a constant number of times, the total cost scales linearly with the input size. Summing these operations yields a proportional number of steps that simplifies directly to O(n).
Space Complexity
O(N) – The space complexity is driven by two main auxiliary data structures: an output results array of size N initialized to hold the answers for each element, and a monotonic stack which acts as the notepad keeping track of indices waiting for a greater number. In the worst-case scenario where the input array is strictly decreasing, the stack will store all N indices during the first pass. Consequently, the combined memory for the results array and the stack scales linearly with the input size N, leading to an auxiliary space complexity of O(N).

Edge Cases

Empty or null input array
How to Handle:
Return an empty array immediately to prevent null pointer exceptions and unnecessary processing.
Single-element array
How to Handle:
Return an array containing negative one since no greater element can exist in a circular array of size one.
Strictly decreasing circular array
How to Handle:
The monotonic stack will fail to find any greater elements across both passes, correctly assigning negative one to all positions.
Array with all identical values
How to Handle:
The stack will process duplicate values without finding a strictly greater element, resulting in an output array of all negative ones.
Array containing negative numbers and zeros
How to Handle:
Numeric comparisons treat negative numbers, zeros, and positives uniformly, ensuring correct relative greater-than determinations.
Extremely large inputs up to the maximum constraints
How to Handle:
Iterating twice over the array using a monotonic stack guarantees linear time complexity and avoids memory overhead.
Maximum and minimum integer boundary values
How to Handle:
Standard integer comparisons handle extreme limits safely without triggering overflow during standard relational checks.
0/245 completed