Skip to content

Commit 838e96b

Browse files
author
Gonzalo Diaz
committed
[Hacker Rank] Interview Preparation Kit: Stacks and Queues: Balanced Brackets. Solved ✅.
1 parent 767c1cc commit 838e96b

File tree

4 files changed

+192
-0
lines changed

4 files changed

+192
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# [Balanced Brackets](https://www.hackerrank.com/challenges/balanced-brackets/)
2+
3+
Given a string containing three types of brackets, determine if it is balanced.
4+
5+
- Difficulty: `#medium`
6+
- Category: `#ProblemSolvingIntermediate` `#stacksAndQueues`
7+
8+
A bracket is considered to be any one of the following characters:
9+
(, ), {, }, [, or ].
10+
11+
Two brackets are considered to be a matched pair if the an opening bracket
12+
(i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or })
13+
of the exact same type. There are three types of matched pairs of brackets:
14+
[], {}, and ().
15+
16+
A matching pair of brackets is not balanced if the set of brackets it encloses
17+
are not matched. For example, {[(])} is not balanced because the contents
18+
in between { and } are not balanced.
19+
The pair of square brackets encloses a single, unbalanced opening bracket,
20+
(, and the pair of parentheses encloses a single,
21+
unbalanced closing square bracket, ].
22+
23+
By this logic, we say a sequence of brackets is balanced if
24+
the following conditions are met:
25+
26+
- It contains no unmatched brackets.
27+
- The subset of brackets enclosed within the confines of a matched
28+
pair of brackets is also a matched pair of brackets.
29+
30+
Given `n` strings of brackets, determine whether each sequence
31+
of brackets is balanced. If a string is balanced, return `YES`.
32+
Otherwise, return `NO`.
33+
34+
## Function Description
35+
36+
Complete the function isBalanced in the editor below.
37+
38+
isBalanced has the following parameter(s):
39+
40+
- `string s`: a string of brackets
41+
42+
## Returns
43+
44+
- `string`: either `YES` or `NO`
45+
46+
## Input Format
47+
48+
The first line contains a single integer `n`, the number of strings.
49+
Each of the next `n` lines contains a single string `s`, a sequence of brackets.
50+
51+
## Constraints
52+
53+
- $ 1 \leq n \leq 10^3 $
54+
- $ 1 \leq \lvert s \rvert \leq 10^3 $, where $ \lvert s \rvert $ is the length
55+
of the sequence.
56+
- All chracters in the sequences ∈ { `{`, `}`, `(`, `)`, `[`, `]` }.
57+
58+
## Output Format
59+
60+
For each string, return YES or NO.
61+
62+
## Sample Input
63+
64+
```text
65+
STDIN Function
66+
----- --------
67+
3 n = 3
68+
{[()]} first s = '{[()]}'
69+
{[(])} second s = '{[(])}'
70+
{{[[(())]]}} third s ='{{[[(())]]}}'
71+
```
72+
73+
## Sample Output
74+
75+
```text
76+
YES
77+
NO
78+
YES
79+
```
80+
81+
## Explanation
82+
83+
The string {[()]} meets both criteria for being a balanced string.
84+
The string {[(])} is not balanced because the brackets enclosed
85+
by the matched pair { and } are not balanced: [(]).
86+
The string {{[[(())]]}} meets both criteria for being a balanced string.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { describe, expect, it } from '@jest/globals';
2+
3+
import { isBalanced } from './balanced_brackets';
4+
import TEST_CASES from './balanced_brackets.testcases.json';
5+
6+
describe('isBalanced', () => {
7+
it('isBalanced test cases', () => {
8+
expect.assertions(8);
9+
10+
const __YES__ = 'YES';
11+
12+
TEST_CASES.forEach((testSet) => {
13+
testSet?.tests.forEach((test) => {
14+
const result = isBalanced(test.input) === __YES__;
15+
16+
expect(result).toStrictEqual(test.expected);
17+
});
18+
});
19+
});
20+
});
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
[
2+
{
3+
"title": "Sample Test Case 0",
4+
"tests":
5+
[
6+
{
7+
"input": "{[()]}",
8+
"expected": true
9+
},
10+
{
11+
"input": "{[(])}",
12+
"expected": false
13+
},
14+
{
15+
"input": "{{[[(())]]}}",
16+
"expected": true
17+
}
18+
]
19+
},
20+
{
21+
"title": "Sample Test Case 1",
22+
"tests":
23+
[
24+
{
25+
"input": "{{([])}}",
26+
"expected": true
27+
},
28+
{
29+
"input": "{{)[](}}",
30+
"expected": false
31+
}
32+
]
33+
},
34+
{
35+
"title": "Sample Test Case 1",
36+
"tests":
37+
[
38+
{
39+
"input": "{(([])[])[]}",
40+
"expected": true
41+
},
42+
{
43+
"input": "{(([])[])[]]}",
44+
"expected": false
45+
},
46+
{
47+
"input": "{(([])[])[]}[]",
48+
"expected": true
49+
}
50+
]
51+
}
52+
]
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/stacks_and_queues/balanced-brackets.md]]
3+
*/
4+
5+
const __YES__ = 'YES';
6+
const __NO__ = 'NO';
7+
8+
export function isBalancedCompute(s: string): boolean {
9+
const pairs: Record<string, string> = { '{': '}', '(': ')', '[': ']' };
10+
const brackets: string[] = [];
11+
12+
for (const letter of s.split('')) {
13+
if (letter in pairs) {
14+
brackets.push(letter);
15+
} else if (
16+
brackets.length > 0 &&
17+
pairs[brackets[brackets.length - 1]] === letter
18+
) {
19+
brackets.pop();
20+
} else {
21+
return false;
22+
}
23+
24+
console.debug(letter);
25+
}
26+
27+
return brackets.length <= 0;
28+
}
29+
30+
export function isBalanced(s: string): string {
31+
return isBalancedCompute(s) ? __YES__ : __NO__;
32+
}
33+
34+
export default { isBalanced };

0 commit comments

Comments
 (0)