#leetcode #python #timecomplexity
Q. Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Solution -
Optimized way - Note - this is sample code.. we cannot use angle brackets in description, so I removed them from the code.
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) - List[int]:
d = {}
stack = []
ans = []
for i in range(len(nums2)-1,-1,-1):
while stack and nums2[i] = stack[-1]:
stack.pop()
if stack:
d[nums2[i]] = stack[-1]
else:
d[nums2[i]] = -1
stack.append(nums2[i])
for y in nums1:
if y in d:
ans.append(d[y])
return ans
#python #leetcodesolutions #dsa #pythoninterviewquestions
Python Developer Interview Questions Answers
Top 10 Python Developer Interview Questions Answer
Mostly asked Python Developer Interview Questions Answer
Commonly asked Python Developer Interview Questions Answer
Tags -
Python leetcode problems
leetcode two sum
leetcode solutions
leetcode hindi
two sum python
two sum problem
On this page of the site you can watch the video online Leetcode 496. Next Greater Element I | Hindi | Python | Leetcode | Optimized way with a duration of hours minute second in good quality, which was uploaded by the user DataEngineering360 08 December 2025, share the link with friends and acquaintances, this video has already been watched 251 times on youtube and it was liked by 4 viewers. Enjoy your viewing!