LC 739 & LC 496 & LC 503


Solution to LeetCode 739 Daily Temperatures, LeetCode 496 Next Greater Element I, and LeetCode 503 Next Greater Element II.

When you can use monotonic stack: given a 1-d array, find the index of the number which is the closest larger / smaller number of the current number. Time complexity O(n).

LeetCode 739

Daily Temperatures (Medium) [link]

Brute Force solution: time complexity O(n^2).

Using monotonic stack: time complexity O(n). Keep track of the index in a stack in increasing order of the values from top to bottom. Then the resulting table is result[stack.top()] = i-stack.top().

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        result = [0]*len(temperatures)
        stack = [0] # index of the temperatures[0]
        for i in range(1, len(temperatures)):
            if temperatures[i] <= temperatures[stack[-1]]:
                stack.append(i)
            else:
                while len(stack) != 0 and temperatures[i] > temperatures[stack[-1]]:
                    result[stack[-1]] = i-stack[-1]
                    stack.pop()
                stack.append(i)
        return result

LeetCode 496

Next Greater Element I (Easy) [link]

Time complexity O(n+m).

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = [-1] * len(nums1)
        stack = [0]
        for i in range(1, len(nums2)):
            if nums2[i] <= nums2[stack[-1]]:
                stack.append(i)
            else:
                while len(stack) !=0 and nums2[i] > nums2[stack[-1]]:
                    if nums2[stack[-1]] in nums1:
                        ind = nums1.index(nums2[stack[-1]])
                        result[ind] = nums2[i]
                    stack.pop()
                stack.append(i)
        return result

LeetCode 503

Next Greater Element II (Medium) [link]

We are going to find the next greater number in a circular integer array. The idea is to concatenate two input arrays and solve the problem as LC 496.

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        res = [-1] * len(nums)
        stack = [0]
        for i in range(1, len(nums)*2):
            if nums[i%len(nums)] <= nums[stack[-1]]:
                stack.append(i%len(nums))
            else:
                while (len(stack) != 0 and nums[i%len(nums)] > nums[stack[-1]]):
                    res[stack[-1]] = nums[i%len(nums)]
                    stack.pop()
                stack.append(i%len(nums))
        return res

Note that all the solution above can be simplified to avoid if-else.


  TOC