Skip to content

Commit b7889a5

Browse files
committed
Update stack algorithms
1 parent 8b25a9e commit b7889a5

File tree

13 files changed

+596
-242
lines changed

13 files changed

+596
-242
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ List of Programs related to data structures and algorithms
116116

117117
| No. | Name | Source | Playground | Documentation | Level | Pattern |
118118
| :-: | :----------------- | :------------------------------------------------------------------------------------------------------------------------------------------------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------: | :----: | :------------------------: |
119-
| 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 |
119+
| 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.md) | Easy | Stack push & pop |
120120
| 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 |
121121
| 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 |
122122
| 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 |

src/javascript/algorithms/stack/1.sortStack/sortStack.js

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,39 @@
11
class MyStack {
2-
32
constructor() {
4-
this.array = []; // Array is used to implement stack
3+
this.items = [];
54
}
65

7-
// List of main functions of stack data structure
8-
6+
// Core stack operations
97
push(value) {
10-
// push an element into the array
11-
this.array.push(value);
8+
this.items.push(value);
129
}
1310

1411
pop() {
15-
// Return null if stack is empty
1612
if (this.isEmpty()) {
17-
return null;
13+
throw new Error("Stack Underflow: Cannot pop from an empty stack.");
1814
}
19-
20-
return this.array.pop(); // return top most element from the stack and removes the same element
15+
return this.items.pop();
2116
}
2217

2318
peek() {
24-
// Return null if stack is empty
2519
if (this.isEmpty()) {
26-
return null;
20+
throw new Error("Stack Underflow: Cannot peek from an empty stack.");
2721
}
28-
29-
return this.array[this.array.length - 1]; // return top most element from the stack without removing the element
22+
return this.items[this.items.length - 1];
3023
}
3124

32-
// List of helper functions
33-
25+
// Helper functions
3426
isEmpty() {
35-
return this.array.length === 0; // return true if stack is empty
27+
return this.items.length === 0;
3628
}
3729

3830
size() {
39-
return this.array.length;
31+
return this.items.length;
4032
}
4133

4234
printStack() {
43-
let data = "";
44-
for (let i = 0; i < this.array.length; i++)
45-
data += this.array[i] + " ";
46-
return data;
35+
return this.items.join(' ');
4736
}
48-
4937
}
5038

5139
function sortStack(stack) {
@@ -57,7 +45,7 @@ function sortStack(stack) {
5745
let top = tempStack.pop();
5846
stack.push(top);
5947
}
60-
tempStack.push(temp);
48+
tempStack.push(temp);
6149
}
6250
stack.array = tempStack.array;
6351
}
Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,38 @@
1-
**Description:**
1+
# Sort Stack
2+
3+
Sorting a stack means arranging its elements in ascending order (smallest on top) using only stack operations and an auxiliary stack. This is a classic problem that demonstrates stack manipulation and algorithmic thinking.
4+
The stack is sorted using another temporary stack, without using any other data structures like arrays or linked lists.
5+
6+
7+
## Problem Statement
8+
29
Given a stack of integers `nums`, sort it in ascending order using another temporary stack.
310

4-
## Examples:
5-
Example 1
6-
Input: [8, 2, 4, 1, 5, 3]
11+
## Examples
12+
13+
**Example 1**
14+
Input: [8, 2, 4, 1, 5, 3]
715
Output: [1, 2, 3, 4, 5, 8]
816

9-
Example 2
10-
Input: [6, 5, 4, 3, 2, 1]
17+
**Example 2**
18+
Input: [6, 5, 4, 3, 2, 1]
1119
Output: [1, 2, 3, 4, 5, 6]
1220

13-
**Algorithmic Steps:**
14-
15-
This problem is solved with the help of **stack push & pop** to sort the elements in a particular order. The algorithmic approach can be summarized as follows:
16-
17-
1. Accept the input stack as an argument to sort its elements.
18-
19-
2. Add a preliminary check by verifying the size of the stack less than one or not. If it is, just return from the function.
20-
21-
3. Create a stack implementation(i.e, `myStack`) based on array. It includes push, pop and peek operations.
21+
## Algorithm
2222

23-
4. Create a temporary stack(`tempStack`) for storing the intermediate results inorder to calculate the sorted stack.
24-
25-
5. Iterate over the input stack `stack` until the elements exists in input stack.
26-
27-
6. For each iteration,
28-
1. Get the top value of input stack and store it in `temp` variable.
29-
2. Iterate over the temporary stack until it's size is greater than zero and the top value of temporary stack is greater than temp value.
30-
3. For each above nested iteration, get the top element from temporary stack and push it to the input stack. This step helps to move higher values from temporary stack to insert lower values at the beginning.
31-
4. If the condition of step2 is not satisfied, push the element to the temporary stack.
23+
This problem is solved using stack push and pop operations to sort the elements. The approach is as follows:
3224

33-
7. Update the input stack with the elements of temporary stack to sort the elements in an ascending order.
25+
1. If the stack has less than one element, return immediately.
26+
2. Create a temporary stack (`tempStack`) to store intermediate results.
27+
3. While the input stack is not empty:
28+
- Pop the top element from the input stack and store it in a variable `temp`.
29+
- While `tempStack` is not empty and its top element is greater than `temp`:
30+
- Pop from `tempStack` and push it back to the input stack.
31+
- Push `temp` onto `tempStack`.
32+
4. Once done, transfer all elements from `tempStack` back to the input stack so that they are sorted in ascending order.
3433

35-
**Time and Space complexity:**
3634

37-
This algorithm has a time complexity of `O(n*2)`, where `n` is the number of elements in an array. This is because of traversal over the characters in a stack and temporary stack.
35+
## Complexity
3836

39-
Here, we used stack data structure store the sorted elements in a temporary stack. Hence, the space complexity will be `O(n)`.
37+
- **Time Complexity:** O(n²) in the worst case, due to nested stack operations.
38+
- **Space Complexity:** O(n), for the auxiliary stack.

src/javascript/algorithms/stack/2.balancedBrackets/balancedBrackets.js

Lines changed: 59 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,45 @@
11
class MyStack {
2-
32
constructor() {
4-
this.array = []; // Array is used to implement stack
3+
this.items = [];
54
}
65

7-
// List of main functions of stack data structure
8-
6+
// Core stack operations
97
push(value) {
10-
// push an element into the array
11-
this.array.push(value);
8+
this.items.push(value);
129
}
1310

1411
pop() {
15-
// Underflow if stack is empty
1612
if (this.isEmpty()) {
17-
return "Underflow";
13+
throw new Error("Stack Underflow: Cannot pop from an empty stack.");
1814
}
19-
20-
return this.array.pop(); // return top most element from the stack and removes the same element
15+
return this.items.pop();
2116
}
2217

2318
peek() {
24-
return this.array[this.array.length - 1]; // return top most element from the stack without removing the element
19+
if (this.isEmpty()) {
20+
throw new Error("Stack Underflow: Cannot peek from an empty stack.");
21+
}
22+
return this.items[this.items.length - 1];
2523
}
2624

27-
// List of helper functions
28-
25+
// Helper functions
2926
isEmpty() {
30-
return this.array.length === 0; // return true if stack is empty
27+
return this.items.length === 0;
3128
}
3229

33-
printStack() {
34-
let data = "";
35-
for (let el of this.array)
36-
data += el + " ";
37-
return data;
30+
size() {
31+
return this.items.length;
3832
}
3933

34+
printStack() {
35+
return this.items.join(' ');
36+
}
4037
}
4138

42-
function hasBalancedParentheses(characters) {
39+
function hasBalancedParentheses1(characters) {
4340
const myStack = new MyStack();
4441
if(characters.length === 0) return true;
45-
if(characters.length === 1 || characters.length % 2 !== 0) return false;
42+
if(characters.length % 2 !== 0) return false;
4643

4744
for(const ch of characters) {
4845
switch(ch) {
@@ -85,13 +82,48 @@ function hasBalancedParentheses(characters) {
8582
if(myStack.isEmpty()) return true;
8683
}
8784

88-
let str1 = '()[]{}<>';
89-
let str2 = '[({<>})]';
90-
let str3 = '([)]';
85+
function hasBalancedParentheses2(input) {
86+
const stack = new MyStack();
87+
const bracketMap = {
88+
')': '(',
89+
'}': '{',
90+
']': '[',
91+
'>': '<'
92+
};
93+
const openBrackets = new Set(['(', '{', '[', '<']);
94+
95+
for (const ch of input) {
96+
if (openBrackets.has(ch)) {
97+
stack.push(ch);
98+
} else if (ch in bracketMap) {
99+
if (stack.pop() !== bracketMap[ch]) {
100+
return false;
101+
}
102+
}
103+
}
104+
return stack.isEmpty();
105+
}
106+
107+
// Test cases
108+
const testCases = [
109+
{ input: '()[]{}<>', expected: true },
110+
{ input: '[({<>})]', expected: true },
111+
{ input: '([)]', expected: false },
112+
{ input: '', expected: true },
113+
{ input: '(', expected: false },
114+
];
115+
116+
for (const { input, expected } of testCases) {
117+
const result = hasBalancedParentheses1(input);
118+
console.log(`Input: "${input}" => ${result} (Expected: ${expected})`);
119+
}
120+
121+
console.log("--------------------------------");
91122

92-
console.log(hasBalancedParentheses(str1));
93-
console.log(hasBalancedParentheses(str2));
94-
console.log(hasBalancedParentheses(str3));
123+
for (const { input, expected } of testCases) {
124+
const result = hasBalancedParentheses2(input);
125+
console.log(`Input: "${input}" => ${result} (Expected: ${expected})`);
126+
}
95127

96128

97129

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,46 @@
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,
1+
# Balanced Brackets
32

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.
3+
Balanced brackets is a classic problem that checks whether every opening bracket in a string has a corresponding and correctly ordered closing bracket. This is commonly used in parsing expressions, validating code, and more.
64

7-
## Examples:
8-
Example 1
9-
Input: str = [()[]{}<>]
10-
Output: true
5+
The problem supports the following bracket types: `()`, `{}`, `[]`, `<>`.
116

7+
## Problem Statement
128

13-
Example 2
14-
Input: str = '[({<>})]'
15-
Output: true
9+
Given a string `str` containing the characters '(', ')', '{', '}', '[', ']', '<', and '>', determine whether the input string is valid. A string is valid if:
1610

17-
Example 3
18-
Input: str = '([)]'
19-
Output: false
11+
1. Every open bracket is closed by the same type of bracket.
12+
2. Brackets are closed in the correct order.
2013

14+
## Examples
2115

22-
**Algorithmic Steps:**
16+
**Example 1**
17+
Input: `str = "()[]{}<>"`
18+
Output: `true`
2319

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:
20+
**Example 2**
21+
Input: `str = "[({<>})]"`
22+
Output: `true`
2523

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.
24+
**Example 3**
25+
Input: `str = "([)]"`
26+
Output: `false`
3327

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.
28+
## Algorithm
3529

36-
6. Repeat steps 4-5 until the end of the string.
30+
This problem is solved using stack operations(**push and pop**) to track opening brackets and ensure they are closed in the correct order.
3731

38-
7. Return `false` if the stack is not empty. That means, there are still few characters which are not balanced.
32+
1. If the string is empty, return `true`.
33+
2. If the string has an odd length, return `false` (since brackets must come in pairs).
34+
3. Initialize an empty stack.
35+
4. Iterate over each character in the string:
36+
- If the character is an opening bracket (`(`, `{`, `[`, `<`), push it onto the stack.
37+
- If the character is a closing bracket (`)`, `}`, `]`, `>`):
38+
- If the stack is empty or the top of the stack does not match the corresponding opening bracket, return `false`.
39+
- Otherwise, pop the top element from the stack.
40+
5. After processing all characters, return `true` if the stack is empty (all brackets matched); otherwise, return `false`.
3941

40-
**Time and Space complexity:**
4142

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+
## Complexity
4344

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).
45+
- **Time Complexity:** O(n), where n is the length of the string. This is because of traversal over the characters in a string at most once.
46+
- **Space Complexity:** O(n), for the stack in the worst case (all opening brackets).

0 commit comments

Comments
 (0)