From 85dbd0016f15bd636a7ba1a05d857cffba1679a9 Mon Sep 17 00:00:00 2001 From: Vibhav Sharma <114804486+ouibhav@users.noreply.github.com> Date: Sat, 12 Oct 2024 20:52:29 +0530 Subject: [PATCH 1/2] Create nextGreaterElement.py --- nextGreaterElement.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 nextGreaterElement.py diff --git a/nextGreaterElement.py b/nextGreaterElement.py new file mode 100644 index 0000000000..e3d90a84db --- /dev/null +++ b/nextGreaterElement.py @@ -0,0 +1,23 @@ +def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + hashmap = {} + output = [] + + for i in reversed(nums2): + while stack: + #found nearest greater element + if stack[-1] > i: + hashmap[i] = stack[-1] + stack.append(i) + break + else: + stack.pop() + + #stack is empty initially or was popped till empty + if not stack: + hashmap[i] = -1 + stack.append(i) + + for j in nums1: + output.append(hashmap[j]) + return output From 70742a72f27cab4cbd6b64a6a399dc57b9024f83 Mon Sep 17 00:00:00 2001 From: Vibhav Sharma <114804486+ouibhav@users.noreply.github.com> Date: Sat, 12 Oct 2024 20:57:18 +0530 Subject: [PATCH 2/2] Create nextGreaterElementPython.py --- nextGreaterElementPython.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 nextGreaterElementPython.py diff --git a/nextGreaterElementPython.py b/nextGreaterElementPython.py new file mode 100644 index 0000000000..e3d90a84db --- /dev/null +++ b/nextGreaterElementPython.py @@ -0,0 +1,23 @@ +def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: + stack = [] + hashmap = {} + output = [] + + for i in reversed(nums2): + while stack: + #found nearest greater element + if stack[-1] > i: + hashmap[i] = stack[-1] + stack.append(i) + break + else: + stack.pop() + + #stack is empty initially or was popped till empty + if not stack: + hashmap[i] = -1 + stack.append(i) + + for j in nums1: + output.append(hashmap[j]) + return output