Solving the Balanced Brackets Problem in TypeScript

Karim Adel
Feb 8
2 min read
post_comment1 Comments
post_like3 Likes

we'll explore a solution to the Balanced Brackets problem in TypeScript. This problem involves determining if a string consisting of various types of brackets ('(', ')', '{', '}', '[', ']') is valid or not based on certain criteria.

You can get this problem from here :

#Understanding the Problem

Given a string, we need to check if the brackets within it are balanced. A string is considered balanced if:

  1. Open brackets are closed by the same type of brackets.
  2. Open brackets are closed in the correct order.

For instance:

  • () and ()[]{}{} are balanced strings.
  • (], ([)], and {[}] are not balanced.

#Approach to Solution

To solve this problem, we can utilize a stack data structure. We'll iterate through the characters of the string, pushing opening brackets onto the stack and popping them when we encounter their corresponding closing brackets. At the end, if the stack is empty, the string is considered balanced.

#Solution Implementation

Let's implement the isValidBrackets function:

function isValidBrackets(s: string): boolean {
    const stack: string[] = [];
    const bracketPairs: { [key: string]: string } = {
        '(': ')',
        '[': ']',
        '{': '}'

    for (const char of s) {
        if (bracketPairs[char]) {
            // If the character is an opening bracket, push it onto the stack
        } else {
            // If the character is a closing bracket
            const topBracket = stack.pop(); // Get the top bracket from the stack
            if (!topBracket || bracketPairs[topBracket] !== char) {
                // If there's no matching opening bracket or the brackets don't match, return false
                return false;

    // If the stack is empty, all brackets were balanced
    return stack.length === 0;

#Complexity Analysis

  • Time Complexity: The time complexity of this solution is O(n), where n is the length of the input string. This is because we iterate through each character in the string once.
  • Space Complexity: The space complexity is also O(n) because the stack can contain up to n/2 brackets in the worst case scenario.


In this article, we've explored an efficient solution to the Balanced Brackets problem using TypeScript. By employing a stack-based approach, we can determine whether a string of brackets is valid or not, satisfying the given criteria. This solution provides a clear and concise way to address such problems, demonstrating the importance of algorithmic thinking in solving coding challenges.

You are not logged in.