Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# [Balanced Brackets](https://www.hackerrank.com/challenges/balanced-brackets/)

Given a string containing three types of brackets, determine if it is balanced.

- Difficulty: `#medium`
- Category: `#ProblemSolvingIntermediate` `#stacksAndQueues`

A bracket is considered to be any one of the following characters:
(, ), {, }, [, or ].

Two brackets are considered to be a matched pair if the an opening bracket
(i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or })
of the exact same type. There are three types of matched pairs of brackets:
[], {}, and ().

A matching pair of brackets is not balanced if the set of brackets it encloses
are not matched. For example, {[(])} is not balanced because the contents
in between { and } are not balanced.
The pair of square brackets encloses a single, unbalanced opening bracket,
(, and the pair of parentheses encloses a single,
unbalanced closing square bracket, ].

By this logic, we say a sequence of brackets is balanced if
the following conditions are met:

- It contains no unmatched brackets.
- The subset of brackets enclosed within the confines of a matched
pair of brackets is also a matched pair of brackets.

Given `n` strings of brackets, determine whether each sequence
of brackets is balanced. If a string is balanced, return `YES`.
Otherwise, return `NO`.

## Function Description

Complete the function isBalanced in the editor below.

isBalanced has the following parameter(s):

- `string s`: a string of brackets

## Returns

- `string`: either `YES` or `NO`

## Input Format

The first line contains a single integer `n`, the number of strings.
Each of the next `n` lines contains a single string `s`, a sequence of brackets.

## Constraints

- $ 1 \leq n \leq 10^3 $
- $ 1 \leq \lvert s \rvert \leq 10^3 $, where $ \lvert s \rvert $ is the length
of the sequence.
- All chracters in the sequences ∈ { `{`, `}`, `(`, `)`, `[`, `]` }.

## Output Format

For each string, return YES or NO.

## Sample Input

```text
STDIN Function
----- --------
3 n = 3
{[()]} first s = '{[()]}'
{[(])} second s = '{[(])}'
{{[[(())]]}} third s ='{{[[(())]]}}'
```

## Sample Output

```text
YES
NO
YES
```

## Explanation

The string {[()]} meets both criteria for being a balanced string.
The string {[(])} is not balanced because the brackets enclosed
by the matched pair { and } are not balanced: [(]).
The string {{[[(())]]}} meets both criteria for being a balanced string.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from '@jest/globals';

import { isBalanced } from './balanced_brackets';
import TEST_CASES from './balanced_brackets.testcases.json';

describe('isBalanced', () => {
it('isBalanced test cases', () => {
expect.assertions(8);

const __YES__ = 'YES';

TEST_CASES.forEach((testSet) => {
testSet?.tests.forEach((test) => {
const result = isBalanced(test.input) === __YES__;

expect(result).toStrictEqual(test.expected);
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
[
{
"title": "Sample Test Case 0",
"tests":
[
{
"input": "{[()]}",
"expected": true
},
{
"input": "{[(])}",
"expected": false
},
{
"input": "{{[[(())]]}}",
"expected": true
}
]
},
{
"title": "Sample Test Case 1",
"tests":
[
{
"input": "{{([])}}",
"expected": true
},
{
"input": "{{)[](}}",
"expected": false
}
]
},
{
"title": "Sample Test Case 1",
"tests":
[
{
"input": "{(([])[])[]}",
"expected": true
},
{
"input": "{(([])[])[]]}",
"expected": false
},
{
"input": "{(([])[])[]}[]",
"expected": true
}
]
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/stacks_and_queues/balanced-brackets.md]]
*/

const __YES__ = 'YES';
const __NO__ = 'NO';

export function isBalancedCompute(s: string): boolean {
const pairs: Record<string, string> = { '{': '}', '(': ')', '[': ']' };
const brackets: string[] = [];

for (const letter of s.split('')) {
if (letter in pairs) {
brackets.push(letter);
} else if (
brackets.length > 0 &&
pairs[brackets[brackets.length - 1]] === letter
) {
brackets.pop();
} else {
return false;
}

console.debug(letter);
}

return brackets.length <= 0;
}

export function isBalanced(s: string): string {
return isBalancedCompute(s) ? __YES__ : __NO__;
}

export default { isBalanced };