Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nextGreaterElement.py #7782

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

nextGreaterElement.py #7782

wants to merge 3 commits into from

Conversation

ouibhav
Copy link

@ouibhav ouibhav commented Oct 12, 2024

#Problem :
Next Greater Element
The nextGreaterElement function takes two lists of integers, nums1 and nums2, and returns a list where each element in nums1 is replaced by the next greater element from nums2. If there is no greater element for a particular element, it is replaced with -1.

#Explanation:
Objective: For each element in nums1, find the first greater element that appears to its right in nums2. If no such element exists, return -1.
Steps:
Stack and Hashmap Setup:

The function uses a stack to keep track of elements in nums2 as it traverses the list from right to left.
A hashmap stores the next greater element for each number in nums2.
Traversing nums2:

The function iterates over nums2 in reverse order.
For each element, it pops elements from the stack until it finds an element greater than the current one, which becomes the next greater element for the current element.
If the stack is empty or no greater element is found, the current element is mapped to -1.
Building the Output:

After processing nums2, the function iterates over nums1 and appends the next greater element (retrieved from the hashmap) to the output list.

#Example:
For nums1 = [4, 1, 2] and nums2 = [1, 3, 4, 2]:

The function will find that:
4 has no greater element in nums2 (hence, -1).
1's next greater element is 3.
2 has no greater element in nums2 (hence, -1).
The output will be [-1, 3, -1].

#Time Complexity:
The function processes each element of nums2 once (O(n)), and each element of nums1 once (O(m)), so the overall time complexity is O(m + n), where m and n are the lengths of nums1 and nums2 respectively.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant