File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ #https://leetcode.com/problems/next-greater-element-i/submissions/
2
+
3
+ # Approach :
4
+
5
+ # We need to find the next greater element than the current element which is in the right side of the array
6
+
7
+ # Since Nums1 is a subset of Nums2 , we will be finding the next greater element in Nums2 and keep storing it in a Hashmap
8
+ # And return only those values which are are present in Nums1
9
+
10
+ # since we need the immediate next element greater than the current element
11
+ # Create a stack to store an element from the nums , compare the top of the stack with the elements from nums2
12
+ # IF the element from nums is greater than the top of the stack , then store this pair in a hashmap
13
+ # If the element from the nums is lesser than the top of the stack or if the stack is empty , append the element in the stack
14
+ # After the nums2 is iterated , check if there is any element remaining in the stack
15
+ # If there is any element remaining , it means that , these elements dont have any other element greater than it (to the right side of the array)
16
+ # So append these elements to the hashmap as keys with values -1
17
+
18
+ # Lastly , return the list of elements from the hashmap which are present in nums1 i.e the required output
19
+
20
+
21
+ class Solution (object ):
22
+ def nextGreaterElement (self , nums1 , nums2 ):
23
+ """
24
+ :type nums1: List[int]
25
+ :type nums2: List[int]
26
+ :rtype: List[int]
27
+ """
28
+
29
+ stack = []
30
+ d = {}
31
+
32
+ for num in nums2 :
33
+ while stack and stack [- 1 ] < num :
34
+ top = stack .pop ()
35
+ d [top ] = num
36
+
37
+ if not stack or stack [- 1 ] > num :
38
+ stack .append (num )
39
+
40
+ while (stack ):
41
+ rest = stack .pop ()
42
+ d [rest ] = - 1
43
+
44
+ return [d [i ] for i in nums1 ]
45
+
46
+
47
+ # Time Complexity: O(N)
48
+ # Auxiliary Space: O(N)
You can’t perform that action at this time.
0 commit comments