Taro Logo

Next Greater Element I

#97 Most AskedEasy
Topics:
ArraysStacks

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.

Constraints:

  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 104
  • All integers in nums1 and nums2 are unique.
  • All the integers of nums1 also appear in nums2.
Follow up: Could you find an O(nums1.length + nums2.length) solution?

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. Are all elements in `nums1` and `nums2` guaranteed to be distinct, or could there be duplicate values within either array?
  2. Can `nums1` or `nums2` be empty, and is it always guaranteed that `nums1` is a subset of `nums2`?
  3. What is the expected range of the integer values within the arrays, and can they contain negative numbers or zeros?
  4. Should the returned array contain the actual next greater values themselves, or their indices in `nums2`?
  5. If no greater element exists to the right for a particular number in `nums2`, should the result for that element explicitly be `-1`?

Brute Force Solution

Approach

The brute force approach to finding the next greater element involves exhaustively checking every possible option for each item in our smaller group of numbers. We simply look at the larger group of numbers to see what comes next for each item we care about.

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

  1. Pick the first number from the smaller group of items.
  2. Search through the complete group of numbers to find where this exact number is located.
  3. Once you find it there, look only at the numbers that appear directly to its right.
  4. Check each of those numbers one by one to see if any of them are strictly bigger than the number you started with.
  5. If you find a bigger number to the right, note that down as your answer for this item.
  6. If you reach the end and find no bigger numbers, note down that no greater element exists.
  7. Repeat this entire search and check process for the next number in the smaller group, and continue until you have checked every single one.

Code Implementation

def next_greater_element(subset_numbers, complete_numbers):
    answer_results = []

    # Iterate through each query item to find its specific next greater value in the wider array
    for current_number in subset_numbers:
        target_index = -1
        for search_index in range(len(complete_numbers)):
            if complete_numbers[search_index] == current_number:
                target_index = search_index
                break

        found_greater = -1

        # Scan only the elements to the right of the matched position to respect array boundaries
        for right_index in range(target_index + 1, len(complete_numbers)):
            if complete_numbers[right_index] > current_number:
                found_greater = complete_numbers[right_index]
                break

        # Append the discovered greater value or a fallback indicator if none exists
        answer_results.append(found_greater)

    return answer_results

Big(O) Analysis

Time Complexity
O(n * m) – Let n be the number of elements in the smaller group and m be the number of elements in the complete group. For each of the n items, we must perform a linear search to find its position in the complete group of size m. Once found, we scan the remaining elements to its right, which takes at most m operations in the worst case. This means we do up to m steps for each of the n elements, resulting in approximately n * m operations. Simplifying this gives a total time complexity of O(n * m).
Space Complexity
O(n) – The space complexity is driven by the data structures used to store intermediate results and perform lookups during the search process. Specifically, we require an auxiliary lookup structure or result mapping that scales with the size of the larger group of numbers, denoted as N. As N grows, the memory allocated for storing these element relationships increases proportionally. Consequently, the total extra memory simplifies to a linear relationship with respect to the input size, yielding O(N) auxiliary space.

Optimal Solution

Approach

To efficiently find the next greater element for a group of numbers, we can scan through the complete collection of numbers while keeping a running track of items waiting for a larger partner. By processing the full sequence ahead of time, we can instantly look up the answer for any specific number without having to search through the collection repeatedly.

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

  1. Look at the complete collection of numbers from right to left, keeping a mental notebook of the items we have seen so far.
  2. As we encounter each number, compare it with the items currently written down in our notebook to see which ones are smaller.
  3. Whenever our current number is bigger than the items in our notebook, cross those smaller items off and record that our current number is their next greater partner.
  4. Add our current number to the notebook so it can be used to find partners for numbers we will check later.
  5. Once this preparation is finished for the entire collection, look at your smaller target group of numbers one by one.
  6. Check our recorded notebook to see if a greater partner was already found and saved for each target number.
  7. If a partner was recorded, write it down; otherwise, note that no greater partner exists for that number.

Code Implementation

def next_greater_element(subset_numbers, complete_collection):
    monotonic_stack = []
    greater_mapping = {}

    # Traverse right to left to precompute the next greater element for each value using a stack.
    for current_number in reversed(complete_collection):
        while monotonic_stack and monotonic_stack[-1] <= current_number:
            monotonic_stack.pop()
        
        if monotonic_stack:
            greater_mapping[current_number] = monotonic_stack[-1]
        else:
            greater_mapping[current_number] = -1
        
        monotonic_stack.append(current_number)

    result_collection = []

    # Look up precomputed results for the subset numbers to build the final answer efficiently.
    for target_number in subset_numbers:
        result_collection.append(greater_mapping.get(target_number, -1))

    return result_collection

Big(O) Analysis

Time Complexity
O(n + m) – Let n be the size of the complete collection of numbers and m be the size of the smaller target group. Processing the complete collection from right to left using a stack ensures each number is pushed and popped at most once, taking O(n) time. Afterwards, looking up the precomputed answer for each of the m target numbers takes constant time per lookup, resulting in O(m) time. Combining these phases, the total operations approximate n + m, which simplifies to O(n + m).
Space Complexity
O(N) – To implement the notebook and record the answers mentioned in the plain English steps, we use a monotonic stack and a hash map. In the worst-case scenario where the entire collection of length N is strictly decreasing, the stack and map will each store up to N elements. Consequently, the auxiliary memory scales linearly with the input size N, simplifying to Big O of N.

Edge Cases

Empty input arrays for nums1 or nums2
How to Handle:
Return an empty array immediately since no lookup operations can be performed.
Minimum-sized arrays where both nums1 and nums2 contain exactly one element
How to Handle:
The algorithm will correctly map the single element to -1 because there are no elements to its right.
Strictly decreasing array in nums2 such as [5, 4, 3, 2, 1]
How to Handle:
The monotonic stack will empty out without finding any greater elements, resulting in -1 for all queries.
Strictly increasing array in nums2 such as [1, 2, 3, 4, 5]
How to Handle:
Each element will successfully find its immediate right neighbor as the next greater element.
Arrays containing negative numbers, zeros, and mixed integer ranges
How to Handle:
The hash map and comparison logic work natively with signed integers without requiring special transformations.
Maximum-sized inputs running into constraints where nums2 is very large
How to Handle:
A linear time monotonic stack and hash map approach ensures the solution scales efficiently within O(N + M) time complexity.
Elements in nums1 appearing at the very last index of nums2
How to Handle:
The precomputed hash map will store -1 for these elements since no elements exist to their right.
Duplicate values within the inputs
How to Handle:
The problem statement specifies that all integers in nums1 and nums2 are distinct, so strict uniqueness is guaranteed.
0/245 completed