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 : https://mentoor.io/prowess/655612050/balanced-brackets
Given a string, we need to check if the brackets within it are balanced. A string is considered balanced if:
For instance:
()
and ()[]{}{}
are balanced strings.(]
, ([)]
, and {[}]
are not balanced.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.
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 stack.push(char); } 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; }
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.