Open In App

JavaScript Program to Find the Length of Longest Balanced Subsequence

Last Updated : 06 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about the Length of the Longest Balanced Subsequence in JavaScript. The Length of the Longest Balanced Subsequence refers to the maximum number of characters in a string sequence that can form a valid balanced expression, consisting of matching opening and closing brackets.

Example:

Input : S = "()())"
Output : 4
()() is the longest balanced subsequence
of length 4.
Input : s = "()(((((()"
Output : 4

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using a stack with for ..of loop

In this approach, we are using a stack to find the length of the longest balanced subsequence in a string. It iterates through the string uses a stack to track opening parentheses and calculates the length of balanced subsequences.

Example: In this example, The balancedSubsequence function uses a stack to track open parenthesis positions in the string s. It calculates the length of the longest balanced subsequence and returns it.

Javascript




function balancedSubsequence(s) {
    const stack = [];
    let maxmimum = 0;
    let currentIndex = -1;
  
    for (const char of s) {
        currentIndex++;
  
        char === '(' ? stack.push(currentIndex) :
            char === ')' && stack.length > 0 ? (
                stack.pop(),
                maxmimum = Math.max(maxmimum, currentIndex -
                    (stack.length > 0
                        ? stack[stack.length - 1] : -1))
            ) : null;
    }
  
    return maxmimum;
}
  
const input = "(()())";
console.log(balancedSubsequence(input));


Output

6

Approach 2: Using Simple Counting

In this approach, we follow simple approach to find the length of the longest balanced subsequence in a string. It counts open and unmatched closing parentheses to determine the maximum length of a valid subsequence.

Example: In this example, the balancedSubsequence function counts valid open and close parentheses in a string s of length n while ignoring invalid close parentheses with no matching open parentheses. It returns the length of the longest balanced subsequence.

Javascript




function balancedSubsequence(s, n) {
    let invalidOpenBraces = 0;
    let invalidCloseBraces = 0;
  
    for (let i = 0; i < n; i++) {
        if (s[i] == '(') {
            invalidOpenBraces++;
        } else {
            if (invalidOpenBraces == 0) {
                invalidCloseBraces++;
            } else {
                invalidOpenBraces--;
            }
        }
    }
    return n - (invalidOpenBraces + invalidCloseBraces);
}
  
let s = "()(((((()";
let n = s.length;
console.log(balancedSubsequence(s, n));


Output

4


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads