How to use a recursive function In Javascript
This approach recursively removes pairs of matching parentheses until either all parentheses are balanced or an imbalance is detected. It continues this process until the string is empty or an imbalance is found, returning true if the parentheses are balanced and false otherwise.
function isValidParentheses(str) {
// Recursive function to check the balance of parentheses
const checkBalance = (s) => {
// Base case: empty string
if (s.length === 0) return true;
// Find the index of the first closing parenthesis
const closingIndex = s.indexOf(')');
if (closingIndex === -1) return false; // If no closing parenthesis is found, parentheses are unbalanced
// Find the index of the nearest opening parenthesis before the closing parenthesis
const openingIndex = s.lastIndexOf('(', closingIndex);
if (openingIndex === -1) return false; // If no opening parenthesis is found, parentheses are unbalanced
// Remove the matched parentheses and continue checking the balance
const remaining = s.slice(0, openingIndex) + s.slice(openingIndex + 1, closingIndex) + s.slice(closingIndex + 1);
return checkBalance(remaining);
};
// Call the recursive function
return checkBalance(str);
}
const inputString = "({()})";
console.log(`Is it a valid Paranthesis ? : ${isValidParentheses(inputString)}`);
Output
Is it a valid Paranthesis ? : false
JavaScript Program to Check Valid Parentheses Using String
In this article, we will learn how we can check valid parentheses of a string, and write a program to check whether the pairs and order of “{ “, ” } “, “(“, “)”, “[“, “]” in the string expression is right or not.
Example:
Input: exp = "[()][()()]()"
Output: True.
Explanation: all of the brackets are properly formed.
Input: exp = "[(])"
Output: False
Explanation: The first and fourth brackets are not balanced because there is a closing ']' before the final '('.
Table of Content
- Using the Stack
- Using Counter
- Using Regular Expression
- Using a Map for Character Matching
- Using a recursive function: