Two phases:
Process with a monotonic decreasing stack. When you pop an element, store its next greater in a hash map.
For each element in , look up its next greater in the hash map. Return if not found. The hash map bridges the two arrays. You compute all next-greater relationships once, then answer queries in . Time: . Space: .