Skip to content

Commit 1637bf9

Browse files
committed
Update stack problems
1 parent 52dbf36 commit 1637bf9

26 files changed

+650
-183
lines changed

README.md

+7-8
Original file line numberDiff line numberDiff line change
@@ -98,15 +98,14 @@ List of Programs related to data structures and algorithms
9898

9999
### Stack
100100

101-
1. Sort Stack: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/sortStack.js)
102-
<!--[Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/sortStack.md) -->
101+
| No. | Name | Source | Playground | Documentation | Level | Pattern |
102+
| :-: | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------------------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------: | :----: | :------------------------: |
103+
| 1 | Sort Stack | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/1.sortStack/sortStack.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/1.sortStack/sortStack.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/1.sortStack/sortStack.js) | Easy | Stack push & pop |
104+
| 2 | Balanced Brackets | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/2.balancedBrackets/balancedBrackets.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/2.balancedBrackets/balancedBrackets.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/2.balancedBrackets/balancedBrackets.md) | Medium | Stack push and pop |
105+
| 3 | Reverse Polish Notation | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/3.reversePolishNotation/reversePolishNotation.js) | [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/3.reversePolishNotation/reversePolishNotation.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/3.reversePolishNotation/reversePolishNotation.md) | Medium | Stack push & pop |
106+
| 4 | Daily Temperatures | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/4.dailyTemperatures/dailyTemperatures.md) | [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/4.dailyTemperatures/dailyTemperatures.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/4.dailyTemperatures/dailyTemperatures.md) | Medium | Monotonic decreasing stack |
107+
| 5 | Number of People See In Queue | [Source](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/5.numberOfPeopleSeeInQueue/numberOfPeopleSeeInQueue.js) | [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/5.numberOfPeopleSeeInQueue/numberOfPeopleSeeInQueue.js) | [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/5.numberOfPeopleSeeInQueue/numberOfPeopleSeeInQueue.md) | Medium | Monotonic decreasing stack |
103108

104-
2. Balanced Brackets: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/balancedBrackets.js)
105-
<!--[Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/balancedBrackets.md)-->
106-
107-
3. Daily Temperatures: [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/dailyTemperatures/dailyTemperatures.js) [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/dailyTemperatures/dailyTemperatures.md)
108-
109-
4. Number of People See In Queue: [JavaScript](https://livecodes.io/?console=open&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/numberOfPeopleSeeInQueue/numberOfPeopleSeeInQueue.js) [Documentation](https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/stack/numberOfPeopleSeeInQueue/numberOfPeopleSeeInQueue.md)
110109

111110
### LinkedList
112111

src/java1/algorithms/stack/BlancedBrackets.java

-84
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
**Description:**
2+
Given a string `str` which contains the characters '(', ')', '{', '}', '[' and ']'. Determine whether an input string is valid or not by following the below conditions,
3+
4+
1. Open brackets must be closed by the same type of brackets in the correct order.
5+
2. Each close bracket has a respective open bracket of the same type.
6+
7+
## Examples:
8+
Example 1
9+
Input: str = [()[]{}<>]
10+
Output: true
11+
12+
13+
Example 2
14+
Input: str = '[({<>})]'
15+
Output: true
16+
17+
Example 3
18+
Input: str = '([)]'
19+
Output: false
20+
21+
22+
**Algorithmic Steps:**
23+
24+
This problem is solved with the help of **stack push and pop** operations to determine the string has valid brackets or not. The algorithmic approach can be summarized as follows:
25+
26+
1. Add preliminary conditions for empty strings, string with one character and odd length. Return `true` if the string is empty and return `false` if the string has one character or length of the string is odd.
27+
28+
2. Create a stack implementation(i.e, `myStack`) based on array. It includes push, pop and peek operations.
29+
30+
3. Iterate over the input string `characters` and verify each character with the conditions of switch block.
31+
32+
4. If the character is an opening bracket(`([{<`), push it to the stack.
33+
34+
5. If the character is a closing bracket(`>}])`), verify the top element of stack equals to respective opening bracket or not. If so, remove/pop the element to indicate the match. Otherwise, return `false` indicating that the given string is not a balanced.
35+
36+
6. Repeat steps 4-5 until the end of the string.
37+
38+
7. Return `false` if the stack is not empty. That means, there are still few characters which are not balanced.
39+
40+
**Time and Space complexity:**
41+
42+
This algorithm has a time complexity of `O(n)`, where `n` is the number of characters in a string. This is because traversal over the characters in a string at most once.
43+
44+
Here, we used stack data structure store the opening brackets. In the worst case, the input string may contain only opening brackets. Hence, the space complexity will be O(n).
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package java1.algorithms.stack.balancedBrackets;
2+
3+
import java.util.Stack;
4+
5+
6+
class BalancedBrackets {
7+
8+
static boolean isBalanced(String characters) {
9+
if(characters.length() == 0) return true;
10+
if(characters.length() == 1 || characters.length()%2 != 0) return false;
11+
12+
Stack<Character> myStack = new Stack<>();
13+
char[] text = characters.toCharArray();
14+
for (char x : text) {
15+
switch (x) {
16+
case '{':
17+
case '<':
18+
case '(':
19+
case '[':
20+
myStack.push(x);
21+
break;
22+
case '}':
23+
if (myStack.peek() == '{') {
24+
myStack.pop();
25+
break;
26+
} else {
27+
return false;
28+
}
29+
case '>':
30+
if (myStack.peek() == '<') {
31+
myStack.pop();
32+
break;
33+
} else {
34+
return false;
35+
}
36+
case ')':
37+
if (myStack.peek() == '(') {
38+
myStack.pop();
39+
break;
40+
} else {
41+
return false;
42+
}
43+
case ']':
44+
if (myStack.peek() == '[') {
45+
myStack.pop();
46+
break;
47+
} else {
48+
return false;
49+
}
50+
}
51+
}
52+
return myStack.empty();
53+
}
54+
55+
public static void main(String args[]) {
56+
String str1 = "()[]{}<>";
57+
String str2 = "[({<>})]";
58+
String str3 = "([)]>";
59+
System.out.println(isBalanced(str1));
60+
System.out.println(isBalanced(str2));
61+
System.out.println(isBalanced(str3));
62+
}
63+
}

src/java1/algorithms/stack/BalancedParentheses.java src/java1/algorithms/stack/balancedParentheses/BalancedParentheses.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//Hashmap:- TC:O(n) SC:O(n)
2-
package java1.algorithms.stack;
2+
package java1.algorithms.stack.balancedParentheses;
33

44
import java.util.*;
55

src/java1/algorithms/stack/balancedParentheses/BalancedParentheses.md

Whitespace-only changes.

src/java1/algorithms/stack/dailyTemperatures/DailyTemperatures.md

+16-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
**Description:**
2+
Given an array of integers `temperatures`, which represents the daily temperatures in a city. For each temperature, calculate how many days one would have to wait for a warmer temperature than the current day. i.e, Find an array `answer` such that `answer[i]` represents the number of days you have to wait after the `i`th day to get a warmer temperature.
3+
4+
**Note:** If there is no future day with a warmer temparature, just return 0.
5+
6+
## Examples:
7+
Example 1
8+
Input: temperatures1 = [72,73,74,70,68,71,75,72]
9+
Output: [1, 1, 4, 2, 1, 1, 0, 0]
10+
11+
Example 2
12+
Input: temperatures2 = [10, 20, 30,40,50,60,70]
13+
Output: [1, 1, 1, 1, 1, 1, 0]
14+
115
**Algorithmic Steps**
216
This problem is solved with the help of monotonic decreasing stack. The algorithmic approach can be summarized as follows:
317

@@ -16,6 +30,6 @@ This problem is solved with the help of monotonic decreasing stack. The algorith
1630
7. Return the days array which indicate elements of number of days to get a warmer temperature
1731

1832
**Time and Space complexity:**
19-
This algorithm has a time complexity of O(n)(i.e, O(n + n)), where n is the number of days in the temperatures list. This is because each element is processed by pushing an element into a stack and then processed again when the element is popped-out. Here, each element is pushed and popped at most once with a linear time.
33+
This algorithm has a time complexity of `O(n)(i.e, O(n + n))`, where n is the number of days in the temperatures list. This is because each element is processed by pushing an element into a stack and then processed again when the element is popped-out. Here, each element is pushed and popped at most once with a linear time.
2034

21-
Also, it takes space complexity of O(n) with the use of stack data structure. In the worst case(all temperatures in decreasing order), the stack will contain all temperature indices.
35+
Also, it takes space complexity of `O(n)` with the use of stack data structure. In the worst case(all temperatures in decreasing order), the stack will contain all temperature indices.

src/java1/algorithms/stack/numberOfPeopleSeeInQueue/NumberOfPeopleSeeInQueue.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ private static int[] canSeePersonsCount(int[] heights) {
1010
int[] visibilityCount = new int[length];
1111
Stack<Integer> stack = new Stack<>();
1212

13-
1413
for(int i=length-1; i>-1; i--) {
15-
while(!stack.isEmpty() && stack.peek() < heights[i]) {
14+
while(!stack.isEmpty() && heights[i] > stack.peek()) {
1615
stack.pop();
1716
++visibilityCount[i];
1817
}
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
**Description:**
2+
Given an array `heights` of distinct integers where `heights[i]` represents the height of the `i`th person. These heights represents `n` people standing in a queue numbered from `0` to `n - 1` in left to right order. Return an array `answer`, where `answer[i]` is the number of people that person `i` can see to their right in the queue.
3+
4+
## Examples:
5+
Example 1
6+
Input: heights1 = [10,6,8,5,11,9]
7+
Output: [3, 1, 2, 1, 1, 0]
8+
9+
Example 2
10+
Input: heights2 = [6, 5, 4, 3, 2, 1]
11+
Output: [1, 1, 1, 1, 1, 0 ]
12+
13+
Example 3
14+
Input: heights2 = [1, 2, 3, 4, 5, 6]
15+
Output: [1, 1, 1, 1, 1, 0 ]
16+
117
**Algorithmic Steps**
218
This problem is solved with the help of monotonic decreasing stack. The algorithmic approach can be summarized as follows:
319

@@ -9,16 +25,16 @@ This problem is solved with the help of monotonic decreasing stack. The algorith
925

1026
4. Iterate over the input array using an iteration variable `i` from backwards(i.e, from end of array to 0). This reverse iteration aligns with the direction of visibility (i.e,rightwards)
1127

12-
5. Inside the loop(step4), create a while loop to pop elements from stack if the top element is less than current person's height. Also, as part of this nested loop, increment the visibility count by 1 because popped person is directly visible
28+
5. Inside the loop(step4), create a while loop to pop elements from stack if current person's height is greater than the top element. Also, as part of this nested loop, increment the visibility count by 1 because popped person is directly visible
1329
to the current person.
1430

15-
5. Upon removing all the shorter people from the previous step, if the stack is still not empty, it indicates that there is atleast one taller person compared to the current person. In this case, the visibility count is incremented by 1.
31+
6. Upon removing all the shorter people from the previous step, if the stack is still not empty, it indicates that there is atleast one taller person compared to the current person. In this case, the visibility count is incremented by 1.
1632

17-
6. Add the current taller person height to the stack.
33+
7. Add the current taller person height to the stack.
1834

19-
7. Return the visibility count array which indicate number of persions of visible at each position.
35+
8. Return the visibility count array which indicate number of persions of visible at each position.
2036

2137
**Time and Space complexity:**
22-
This algorithm has a time complexity of O(n), where n is the number of people a person can see. This is because we are iterating the array only once. However, each element performs multiple comparisons along with pop operations from the stack until a higher height is found. In the worst, each element will be pushed and popped from the stack once, leads to time complexity of O(n). So the overall time complexity is O(n).
38+
This algorithm has a time complexity of `O(n)`, where `n` is the number of people a person can see. This is because we are iterating the array only once. However, each element performs multiple comparisons along with pop operations from the stack until a higher height is found. In the worst, each element will be pushed and popped from the stack once, leads to time complexity of `O(n)`. So the overall time complexity is `O(n)`.
2339

24-
Also, it takes space complexity of O(n) with the help of stack and array data structures, using `n` number of elements. In the worst case(when heights are in ascending order), the stack will contain all people heights.
40+
Also, it takes space complexity of `O(n)` with the help of stack and array data structures, using `n` number of elements. In the worst case(when heights are in ascending order), the stack will contain all people heights.

0 commit comments

Comments
 (0)