File size: 2,508 Bytes
3c88a0f
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "cp-10005", "name": "LeetCode 0496: Next Greater Element I"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Next Greater Element I (Difficulty: Easy)\nTags: Array, Hash Table, Stack, Monotonic Stack\n\nThe 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.\nYou are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.\nFor 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.\nReturn an array ans of length nums1.length such that ans[i] is the next greater element as described above.\n\nExample 1:\nInput: nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput: [-1,3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n\nExample 2:\nInput: nums1 = [2,4], nums2 = [1,2,3,4]\nOutput: [3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.\n\nConstraints:\n- 1 <= nums1.length <= nums2.length <= 1000\n- 0 <= nums1[i], nums2[i] <= 10^4\n- All integers in nums1 and nums2 are unique.\n- All the integers of nums1 also appear in nums2."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time:  O(m + n)\n# Space: O(m + n)\n\nclass Solution(object):\n    def nextGreaterElement(self, findNums, nums):\n        \"\"\"\n        :type findNums: List[int]\n        :type nums: List[int]\n        :rtype: List[int]\n        \"\"\"\n        stk, lookup = [], {}\n        for num in nums:\n            while stk and num > stk[-1]:\n                lookup[stk.pop()] = num\n            stk.append(num)\n        while stk:\n            lookup[stk.pop()] = -1\n        return map(lambda x : lookup[x], findNums)\n\n"}}