Next Greater Element
The next greater element of some element xx
You are given two distinct 0-indexed integer arrays nums1nums2nums1nums2
For each 0 <= i < nums1.lengthjnums1[i] == nums2[j]next greater elementnums2[j]nums2-1
Return an array ansnums1.lengthans[i]
Example 1
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
4 is highlighted in nums2 = [1, 3,
1 is highlighted in nums2 = [
2 is highlighted in nums2 = [1, 3, 4,
Example 2
Output: [3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
2 is highlighted in nums2 = [1,
4 is highlighted in nums2 = [1, 2, 3,
Follow-up:
Contents
Solution 1 - scan through nums2 array for every number in nums1
In this approach, we are going to loop through each number in nums1nums2
public class NextGreaterElement1 {
/* iteration over both arrays and for each number in nums1, find next immediate
greater element if exists from nums2 */
static int[] usingIterateOverArrays(int[] nums1, int[] nums2) {
for(int i=0;i <nums1.length; i++) {
int num = nums1[i];
int nextGreater=0;
for(int j=0; j<nums2.length; j++) {
if(nums2[j] == num) {
nextGreater = -1;
}
if(nextGreater == -1 && nums2[j] > num) {
nextGreater = nums2[j];
break;
}
}
nums1[i] = nextGreater;
}
return nums1;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n * m) time where nnums2mnums1nums1nums2
Space complexity: O(m) for the answer array, in the above implementation, we are modifying input array nums1
Solution 2 - scan through nums2 and capture next possible greater element for every number (Answer to the follow-up question)
Main intution of this approach is that, we are going to loop through nums2HashMapnums1
Implementation details
If we have to capture next greater element for every number in nums2nums2O(n2)
Since we are looking for next immediate greater element, there is a better way to capture that using a Stack
-
We will be initializing a
, which will be empty in the beginning and aStack that we will be using to store the number from array as key and its next immediate greater element as value.HashMap<Integer, Integer> -
Then, we are going to loop through the numbers in
array, and for each number innums2 arraynums2 check if this number is greater than the number at top of thecurrentNum :Stack-
If it is, then add this to the
we have created,HashMap as key and number fromcurrentNum as value.Stack -
If it is not greater than the number from
, then add this number to theStack .Stack
-
If it is, then add this to the
-
By the end of this loop,
will contain the next greater elements if it finds one, and theHashMap may still have some elements, if there is no greater element found.Stack -
Then, for any remaining elements in
, we simply add them to theStack with value asHashMap since there is no greater element found.-1 -
Finally, we can go through numbers in
array and get the next greater element that we have already computed fromnums1 and return the result.HashMap
Let's understand with an example, say nums1 = [4, 1, 2]nums2 = [1, 3, 4, 2]
-
We will be looping through
and find next greater elements for each number in the array.nums2 -
In the first step
, since thecurrentNum = 1 is empty, we will just add this to the stack.StackStack elements 1 Map key value -
Next number is
, now we look at the top element in thecurrentNum = 3 which is 1,Stack is greater than the element coming from stack. So, for elementcurrentNum immediate greater element is1 , so add it to the map. At the same time, we remove3 from stack, since we found answer for it, and add element1 to the stack.3Stack elements 3 Map key value 1 3 -
Next number is
, now we look at the top element in thecurrentNum = 4 which is 3,Stack is greater than the element coming from stack. So, for elementcurrentNum immediate greater element is3 , so add it to the map. At the same time, we remove4 from stack, since we found answer for it, and add element3 to the stack.4Stack elements 4 Map key value 1 3 3 4 -
Next number is
, now we look at the top element in thecurrentNum = 2 which is 4,Stack is not greater than the element coming from stack. So, we simply add it to the stack.currentNumStack elements 2 4 Map key value 1 3 3 4 -
We have now iterated through
aray fully. Now we look at stack and see if it still had any elements left, yes there are two elements left in the stack. So, for these elements we will addnums2 to the map, this is because there are no greater elements found for these. Map now looks like this.-1Map key value 2 -1 4 -1 1 3 3 4 -
Now, we will go through
array and find the next greater element from the map we have prepared above. So, fornums1 , the result array is going to benums1 = [4, 1, 2] .result = [-1, 3, -1]
import java.util.HashMap;
import java.util.Stack;
public class NextGreaterElement1 {
/* For every number in nums2, store next greater element possible in a Map, then loop through nums1
and get greater element from already computed Map */
static int[] usingStackAndMap(int[] nums1, int[] nums2) {
Stack<Integer> stack = new Stack<>();
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums2.length; i++) {
int currentNum = nums2[i];
while(!stack.isEmpty() && currentNum > stack.peek()) {
map.put(stack.pop(), currentNum);
}
stack.push(currentNum);
}
// If stack still have elements left
while(!stack.isEmpty()) {
map.put(stack.pop(), -1);
}
// now, iterate through nums1 array an find the next greatest element from map which we
// stored above
for(int i=0; i<nums1.length; i++) {
nums1[i] = map.get(nums1[i]);
}
return nums1;
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n + m) time where nnums2mnums1nums2nums1O(n)nums1nums2
Space complexity: O(n) for the HashMapStack