How to useTwo Pointers in Javascript

In the Two Pointers approach, initialize two pointers at the start of the string. Increment the second pointer until encountering a closing bracket. Move the first pointer to the next character after the opening bracket. Keep track of the longest balanced subsequence encountered.

Example: This example The function longestBalancedSubsequence iterates through the string, incrementing a counter for each ‘(‘ and decrementing it for each ‘)’. It returns the length of the longest balanced subsequence found.

JavaScript
function longestBalancedSubsequence(s) {
    let maxLength = 0;
    let balance = 0;

    for (const char of s) {
        if (char === '(') {
            balance++;
        } else if (char === ')' && balance > 0) {
            balance--;
            maxLength += 2;
        }
    }

    return maxLength;
}

const input = "(()())";
console.log(longestBalancedSubsequence(input));

Output
6


JavaScript Program to Find the Length of Longest Balanced Subsequence

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.

Table of Content

  • Using a stack with for ..of loop
  • Using Simple Counting
  • Using Two Pointers

Similar Reads

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....

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....

Approach 3: Using Two Pointers

In the Two Pointers approach, initialize two pointers at the start of the string. Increment the second pointer until encountering a closing bracket. Move the first pointer to the next character after the opening bracket. Keep track of the longest balanced subsequence encountered....