Skip to content

Commit

Permalink
Add monotone stack example
Browse files Browse the repository at this point in the history
  • Loading branch information
jsjtzyy committed Feb 14, 2021
1 parent b07b389 commit 1c0b7e3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions MonotoneStack/MonotoneStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
public class MonotoneStack{

/*
* Given an array (i.e. [5, 2, 3, 1, 4]), for each element in the array, find minimum steps to move to find next element larger than itself.
* If such next element doesn't exist, step = -1;
* Using above array as an example, we should return [-1, 1, 2, 1, -1]
*/
public static int[] monotonousStack(int[] nums){
int[] res = new int[nums.length];
Stack<Integer> stack = new Stack<>();
// maintain a stack ensuring ascending order from top to bottom
for(int i = 0; i < nums.length; ++i){
while(!stack.isEmpty() && nums[i] > nums[stack.peek()]){
int index = stack.pop();
res[index] = i - index;
}
stack.push(i);
}
while(!stack.isEmpty()){
int index = stack.pop();
res[index] = -1;
}
// as each element is pushed and popped once, the time complexity is O(n)
return res;
}
}
File renamed without changes.
File renamed without changes.

0 comments on commit 1c0b7e3

Please sign in to comment.