Data Structures19 sections · 729 units
Open in Course

Next Greater - Algorithm

Stack + hash map

Two phases:

1.1. Process nums2nums2 with a monotonic decreasing stack. When you pop an element, store its next greater in a hash map.

2.2. For each element in nums1nums1, look up its next greater in the hash map. Return 1-1 if not found. The hash map bridges the two arrays. You compute all next-greater relationships once, then answer queries in O(1)O(1). Time: O(n+m)O(n + m). Space: O(n)O(n).