Next Greater Element

496. Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Thought Process:

  • Iterate over the numbers in nums2, create a hashmap annotating the next greater element for each number.
  • This annotation is done via a stack, before we push a number onto the stack, we check the top element on the stack. If the top element is smaller than the push element, we insert this key value pair to the hashmap and pop the top.
  • Once the top element is greater or equal to the push element or the stack becomes empty, we can resume the push.
def nextGreaterElement(nums1, nums2):
    mapping = defaultdict(lambda: -1)
    stack = []
    for num in nums2:
        while stack and stack[-1] < num: mapping[stack.pop()] = num
        stack.append(num)

    return [mapping[num] for num in nums1]

503. Next Greater Element II

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. 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, output -1 for this number.

Thought Process:

  • Since the array is circular, we have to scan at least twice to make sure we find each number the next greater number.
def nextGreaterElements(nums):
    next_greater = [-1] * len(nums)
    stack = []
    for i, num in chain(enumerate(nums), enumerate(nums)):
        while stack and nums[stack[-1]] < num: next_greater[stack.pop()] = num
        stack.append(i)
    return next_greater

Monotonic stack

  • 456. 132 Pattern

    Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
    Return true if there is a 132 pattern in nums, otherwise, return false.

def find132pattern(nums):
    n = len(nums)
    stack = [(0, nums[0])]
    min_upto = nums[0]
    for i, num in enumerate(nums[1:], 1):
        while stack and nums[stack[-1][0]] < num: stack.pop()
        if stack and nums[stack[-1][0]] > num > stack[-1][1]: return True
        min_upto = min(min_upto, num)
        stack.append((i, min_upto))
    return False
  • 84. Largest Rectangle in Histogram

    Given an array of integers heights representing the histogram’s bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

def largestRectangleArea(heights):
    heights.append(0)
    stack = [-1]
    max_area = 0
    for i, height in enumerate(heights):
        while stack and heights[stack[-1]] > height:
            h = heights[stack.pop()]
            w = i - stack[-1] - 1
            max_area = max(max_area, h * w)
        stack.append(i)
    heights.pop()
    return max_area

739. Daily Temperatures

Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

Monotonic decreasing stack

# left to right
def dailyTemperatures(temperatures):
    result = [0] * len(temperatures)
    stack = []
    for day in range(len(temperatures)):
        temp = temperatures[day]
        while stack and temp > temperatures[stack[-1]]:
            prev_day = stack.pop()
            result[prev_day] = day - prev_day
        stack.append(day)
    return result

# right to left n
def dailyTemperatures(temperatures):
    result = [0] * len(temperatures)
    stack = []
    for day in range(len(temperatures) - 1, -1, -1):
        temp = temperatures[day]
        while stack and temp >= temperatures[stack[-1]]:
            stack.pop()
        if stack:
            result[day] = stack[-1] - day
        stack.append(day)
    return result