Stack
https://medium.com/@gregsh9.5/monotonic-queue-notes-980a019d5793 https://medium.com/algorithms-and-leetcode/monotonic-queue-explained-with-leetcode-problems-7db7c530c1d6
Add Strings to stack, pop if meet "..".
public String simplifyPath(String path) {
String[] strs = path.split("/");
Stack<String> stack = new Stack<>();
for (int i = 1; i < strs.length; i++) {
if (strs[i].equals("..") && !stack.isEmpty()) {
stack.pop();
} else if (!strs[i].equals(".")
&& !strs[i].equals("..")
&& !strs[i].equals("")) {
stack.add(strs[i]);
}
}
StringBuilder sb = new StringBuilder("/");
for (String s : stack) {
sb.append(s).append("/");
}
return sb.length() != 1
? sb.deleteCharAt(sb.length() - 1).toString()
: sb.toString();
}Next Greater Element
Find the next greater element in array, if no such element, return -1.
Pointer move from end to beginning, use a stack to store all element, but pop values which are smaller than the current value, this way we can keep a non-increasing sequence.
T: O(n) S: O(n)
Before add new element. Add the previous min to the stack.
Use two stacks to flip to get queue.
Loop over the token strings and add to a stack if it is a number. Alternatively run operation if it is an operator.
Use two stacks, one to store result and the other one store numbers.
meet "[", add to stack and reset current elements
meet "]", pop from stack and aggregate results
Same as the problem above. Answer is the distance between peek value and current index.
T: O(n) S: O(n)
Refer to as Next Greater Element.
T: O(n) S: O(n)
Since it is a circular array, one way is looping over the array twice, and maintain the stack and result array. While looping, mod i by n (i % n) as it points to the position on the current array.
If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321.
If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234.
For other cases, we need to process the number from rightmost side (why? because we need to find the smallest of all greater numbers)
Algorithm:
Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “
534976”, we stop at4because4is smaller than next digit9. If we do not find such a digit, then output is “Not Possible”.Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “
534976″, the right side of4contains “976”. The smallest digit greater than4is6.Swap the above found two digits, we get
536974in above example.
Use stack to add element when it is positive. Otherwise, keep popping the previous one when it is smaller than opposite of current, for eg. [2, 3, -10].
When current and previous are exactly opposite, such as [8, -8], only pop. When the previous is negative, continue push current, eg [-2, -1]
Same as 556 above:
find the first increase element i from the right
find the first element larger than
ifrom the rightswap
iandj, reverse fromi + 1to end.
Solution1: Sort and find the start and end of the difference: O(nlogn)
Solution1: Use Monotonic stack to find the smallest start index where it violates the increasing trend. Also find the largest end where it violates the decreasing trend from the back. O(n)
Maintain a deque while going through Keep only the indexes of elements from the current sliding window. Remove indexes of all elements smaller than the current one, since they will not be the maximum ones.
given an n x m matrix and a value k, find minimum values for all sub-matrixes of size k
example: given this matrix:
and a k of
3result:
First for each column calculate the minimum for each sliding window(vertical direction) of k
Then for each pair of row having col width k, run sliding window (horizontal direction) of k on col data from 1.
Similar as the question above. It needs to calculate the difference of an interval. Two deque is needed to get the min and max of the interval. The last element is always the largest or smallest. That:
In min deque, when the last element is larger than current element, poll last
in max deque, when the last element is smaller than current element, poll last
when the element reach to the current element, pop first
As well as maintain the longest interval.
Maintain an increasing monotonic stack. Add a -1 to the stack for easier calculation. When encounter a decreasing element, pop the stack and calculate the max before current element. At the end, clear all elements in the stack and calculate the left over areas.
Use a stack and only keep the elements larger than the new element, as well as aggregate the counts less or equals to the new element.
Use a stack to store previous numbers. Use an operator character to store the last operator. When meet new operator or reach the last digit, perform the operation, aggregate results at last.
Store map: element : count to stack. When meeting brackets, deal with the maps in stack. Otherwise, store elements and their count to map.
Constrained Subsequence Sum
Find the smallest consecutive two values to merge to get min cost. When encounter a number is larger than peek, calculate the product of peek (smaller number) and n or the one before peek. Later cumulate all products.
Save the consecutive character lengths in a stack. When see the same char, and char length equals to k, remove the substring.
Sum of Subarray Minimums
Online Stock Span
Score of Parentheses
Next Greater Element II
Next Greater Element I
Largest Rectangle in Histogram
Trapping Rain Water
Max Value of Equation
Simulate the stack push and pop operations, validate the sequence in popped array and pop in the stack.
2334. Subarray With Elements Greater Than Varying Threshold
Use monotonic stack to find the last smaller element to the left and right, hence get a range of all elements greater than current:
Last updated
Was this helpful?