The Wayback Machine - https://web.archive.org/web/20241008153847/https://www.geeksforgeeks.org/length-of-the-longest-valid-substring/
Open In App

Longest Valid Parentheses Substring

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string str consisting of opening and closing parenthesis ‘(‘ and ‘)‘. Find the length of the longest valid parenthesis substring.

Examples: 

Input: ((()
Output : 2
Explanation : Longest Valid Parentheses Substring is ().

Input: )()())
Output : 4
Explanation: Longest Valid Parentheses Substring is ()() .

[Expected Approach – 1] Using Stack – O(n) Time and O(n) Space:

The idea is to use a stack-based approach to track the indices of unmatched parentheses. It determines the length of valid (well-formed) parentheses substrings by keeping track of the position of the last unmatched closing parenthesis or the starting position of a valid substring.

Follow the steps below to solve the problem:

  • For every opening parenthesis, we push its index onto the stack.
  • For every closing parenthesis, we pop the stack.
  • If the stack becomes empty after popping, it means we’ve encountered an unmatched closing parenthesis, so we push the current index to serve as a base for the next potential valid substring.
  • If the stack is not empty, we calculate the length of the valid substring by subtracting the index at the top of the stack from the current index.
  • A variable maxLength keeps track of the maximum length of valid parentheses encountered during the traversal.

Below is the implementation of the above approach:

C++
// C++ program to find length of the 
// longest valid substring

#include <bits/stdc++.h>
using namespace std;

int maxLength(string s) {
    stack<int> st;

    // Push -1 as the initial index to 
      // handle the edge case
    st.push(-1);
    int maxLen = 0;

    // Traverse the string
    for (int i = 0; i < s.length(); i++) {
        
        // If we encounter an opening parenthesis,
          // push its index
        if (s[i] == '(') {
            st.push(i);
        } else {
            
            // If we encounter a closing parenthesis,
              // pop the stack
            st.pop();

            // If stack is empty, push the current index 
            // as a base for the next valid substring
            if (st.empty()) {
                st.push(i);
            } else {
                
                // Update maxLength with the current length 
                // of the valid parentheses substring
                maxLen = max(maxLen, i - st.top());
            }
        }
    }

    return maxLen;
}

int main() {
  
    string s = ")()())"; 
    cout << maxLength(s) << endl;

    return 0;
}
Java
// Java program to find length of the
// longest valid substring

import java.util.Stack;

class GfG {

    // Function to find the length of the 
    // longest valid parentheses substring
    static int maxLength(String s) {
        Stack<Integer> stack = new Stack<>();

        // Push -1 as the initial index to
          // handle the edge case
        stack.push(-1);
        int maxLen = 0;

        // Traverse the string
        for (int i = 0; i < s.length(); i++) {

            // If we encounter an opening parenthesis, 
              // push its index
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {

                // If we encounter a closing parenthesis, 
                  // pop the stack
                stack.pop();

                // If stack is empty, push the current index 
                // as a base for the next valid substring
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {

                    // Update maxLength with the current length 
                    // of the valid parentheses substring
                    maxLen = Math.max(maxLen, i - stack.peek());
                }
            }
        }

        return maxLen;
    }

    public static void main(String[] args) {
        String s = ")()())";
        System.out.println(maxLength(s));
    }
}
Python
# Python program to find length of the
# longest valid substring

def maxLength(s):
    stack = []

    # Push -1 as the initial index to 
    # handle the edge case
    stack.append(-1)
    max_len = 0

    # Traverse the string
    for i in range(len(s)):

        # If we encounter an opening parenthesis,
        # push its index
        if s[i] == '(':
            stack.append(i)
        else:

            # If we encounter a closing parenthesis, 
            # pop the stack
            stack.pop()

            # If stack is empty, push the current index
            # as a base for the next valid substring
            if not stack:
                stack.append(i)
            else:
              
                # Update maxLength with the current length 
                # of the valid parentheses substring
                max_len = max(max_len, i - stack[-1])

    return max_len

if __name__ == "__main__":
    s = ")()())"
    print(maxLength(s))
C#
// C# program to find length of the
// longest valid substring

using System;
using System.Collections.Generic;

class GfG {

    // Function to find the length of the 
    // longest valid parentheses substring
    static int maxLength(string s) {
        Stack<int> stack = new Stack<int>();

        // Push -1 as the initial index to handle
          //   the edge case
        stack.Push(-1);
        int maxLen = 0;

        // Traverse the string
        for (int i = 0; i < s.Length; i++) {

            // If we encounter an opening parenthesis, 
              // push its index
            if (s[i] == '(') {
                stack.Push(i);
            } else {

                // If we encounter a closing parenthesis, 
                  // pop the stack
                stack.Pop();

                // If stack is empty, push the current index 
                // as a base for the next valid substring
                if (stack.Count == 0) {
                    stack.Push(i);
                } else {

                    // Update maxLength with the current length 
                    // of the valid parentheses substring
                    maxLen = Math.Max(maxLen, i - stack.Peek());
                }
            }
        }

        return maxLen;
    }

    static void Main() {
        string s = ")()())";
        Console.WriteLine(maxLength(s));
    }
}
JavaScript
// JavaScript program to find length of the 
// longest valid substring

function maxLength(s) {
    let stack = [];

    // Push -1 as the initial index to handle
    // the edge case
    stack.push(-1);
    let maxLen = 0;

    // Traverse the string
    for (let i = 0; i < s.length; i++) {
        
        // If we encounter an opening parenthesis, 
        // push its index
        if (s[i] === '(') {
            stack.push(i);
        } else {
            
            // If we encounter a closing parenthesis,
            // pop the stack
            stack.pop();

            // If stack is empty, push the current index 
            // as a base for the next valid substring
            if (stack.length === 0) {
                stack.push(i);
            } else {
                
                // Update maxLength with the current length 
                // of the valid parentheses substring
                maxLen = Math.max(maxLen, i - stack[stack.length - 1]);
            }
        }
    }

    return maxLen;
}

let s = ")()())";
console.log(maxLength(s));

Output
4

Time Complexity: O(n), where n is the size of string.
Auxiliary Space: O(n)

[Expected Approach – 2] Using DP – O(n) Time and O(n) Space:

The idea is to solve this problem using dynamic programming (DP) where dp[i] represents the length of the longest valid parentheses substring ending at index i. If a valid substring ends at i, we calculate and store the length of that substring in dp[i].

Follow the steps below to solve the problem:

  • If we encounter an opening parenthesis, we can’t form a valid substring yet, so we move to the next character.
  • If we encounter a closing parenthesis, we check the previous character to determine if it forms a valid substring.
    • If the previous character is ‘(‘, we have a valid pair, so dp[i] = dp[i-2] + 2 (if i-2 is valid).
    • If the previous character is ‘)’, check if the substring before it forms a valid substring. We use dp[i-1] to determine where the valid substring might start.
  • Also, store the maximum length of valid parentheses during the traversal.

Below is the implementation of the above algorithm. 

C++
// C++ program to find length of the
// longest valid substring using DP
#include <bits/stdc++.h>
using namespace std;

// Function to find the length of the
// longest valid parentheses substring
int maxLength(string s) {

    int n = s.length();
    vector<int> dp(n, 0);
    int maxLen = 0;

    // Traverse the string
    for (int i = 1; i < n; i++) {

        // If we encounter a closing parenthesis
        if (s[i] == ')') {

            // Check if the previous character is an
            // opening parenthesis '('
            if (s[i - 1] == '(') {
                if (i >= 2) {
                    dp[i] = dp[i - 2] + 2;
                }
                else {
                    dp[i] = 2;
                }
            }

            // Check if the previous character is a
            // closing parenthesis ')' and the matching opening
            // parenthesis exists before the valid substring
            else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') {
                if (i - dp[i - 1] >= 2) {
                    dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
                }
                else {
                    dp[i] = dp[i - 1] + 2;
                }
            }

            // Update the maximum length
            maxLen = max(maxLen, dp[i]);
        }
    }

    return maxLen;
}

int main() {
  
    string s = ")()())";
    cout << maxLength(s) << endl;

    return 0;
}
Java
// Java program to find length of the
// longest valid substring using DP
import java.util.*;

class GfG {

    // Function to find the length of the
    // longest valid parentheses substring
    static int maxLength(String s) {

        int n = s.length();
        int[] dp = new int[n];
        int maxLen = 0;

        // Traverse the string
        for (int i = 1; i < n; i++) {

            // If we encounter a closing parenthesis
            if (s.charAt(i) == ')') {

                // Check if the previous character is an
                // opening parenthesis '('
                if (s.charAt(i - 1) == '(') {
                    if (i >= 2) {
                        dp[i] = dp[i - 2] + 2;
                    }
                    else {
                        dp[i] = 2;
                    }
                }

                // Check if the previous character is a
                // closing parenthesis ')' and the matching
                // opening parenthesis exists before the
                // valid substring
                else if (i - dp[i - 1] > 0 
                        && s.charAt(i - dp[i - 1] - 1) == '(') {
                  
                    if (i - dp[i - 1] >= 2) {
                        dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
                    }
                    else {
                        dp[i] = dp[i - 1] + 2;
                    }
                }

                // Update the maximum length
                maxLen = Math.max(maxLen, dp[i]);
            }
        }

        return maxLen;
    }

    public static void main(String[] args) {
        String s = ")()())";

        System.out.println(maxLength(s));
    }
}
Python
#Python program to find length of the
# longest valid substring using DP
def maxLength(s):

    n = len(s)
    dp = [0] * n
    max_len = 0

    # Traverse the string
    for i in range(1, n):

        # If we encounter a closing parenthesis
        if s[i] == ')':

            # Check if the previous character is an opening
            # parenthesis '('
            if s[i - 1] == '(':
                if i >= 2:
                    dp[i] = dp[i - 2] + 2
                else:
                    dp[i] = 2

            # Check if the previous character is a
            # closing parenthesis ')' and the matching opening
            # parenthesis exists before the valid substring
            elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == '(':
                if i - dp[i - 1] >= 2:
                    dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
                else:
                    dp[i] = dp[i - 1] + 2

            # Update the maximum length
            max_len = max(max_len, dp[i])

    return max_len


if __name__ == "__main__":

    s = ")()())"
    print(maxLength(s))
C#
// C# program to find length of the
// longest valid substring using DP
using System;

class GfG {

    // Function to find the length of the
    // longest valid parentheses substring
    static int maxLength(string s) {

        int n = s.Length;
        int[] dp = new int[n];
        int maxLen = 0;

        // Traverse the string
        for (int i = 1; i < n; i++) {

            // If we encounter a closing parenthesis
            if (s[i] == ')') {

                // Check if the previous character is an
                // opening parenthesis '('
                if (s[i - 1] == '(') {
                    if (i >= 2) {
                        dp[i] = dp[i - 2] + 2;
                    }
                    else {
                        dp[i] = 2;
                    }
                }

                // Check if the previous character is a
                // closing parenthesis ')' and the matching
                // opening parenthesis exists before the
                // valid substring
                else if (i - dp[i - 1] > 0
                         && s[i - dp[i - 1] - 1] == '(') {
                    if (i - dp[i - 1] >= 2) {
                        dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
                    }
                    else {
                        dp[i] = dp[i - 1] + 2;
                    }
                }

                // Update the maximum length
                maxLen = Math.Max(maxLen, dp[i]);
            }
        }

        return maxLen;
    }

    static void Main(string[] args) {
        string s = ")()())";

        Console.WriteLine(maxLength(s));
    }
}
JavaScript
// Javascript program to find length of the
// longest valid substring using DP
function maxLength(s) {
    const n = s.length;
    const dp = new Array(n).fill(0);
    let maxLen = 0;

    // Traverse the string
    for (let i = 1; i < n; i++) {

        // If we encounter a closing parenthesis
        if (s[i] === ")") {

            // Check if the previous character is an opening
            // parenthesis '('
            if (s[i - 1] === "(") {
                if (i >= 2) {
                    dp[i] = dp[i - 2] + 2;
                }
                else {
                    dp[i] = 2;
                }
            }

            // Check if the previous character is a
            // closing parenthesis ')' and the matching
            // opening parenthesis exists before the valid
            // substring
            else if (i - dp[i - 1] > 0
                     && s[i - dp[i - 1] - 1] === "(") {
                if (i - dp[i - 1] >= 2) {
                    dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
                }
                else {
                    dp[i] = dp[i - 1] + 2;
                }
            }

            // Update the maximum length
            maxLen = Math.max(maxLen, dp[i]);
        }
    }

    return maxLen;
}

const s = ")()())";
console.log(maxLength(s));

Output
4

Time Complexity: O(n), where n is the size of string.
Auxiliary Space: O(n)

[Expected Approach – 3] Using Two Traversals – O(n) Time and O(1) Space:

The idea is to solve the problem using two traversals of the string, one from left to right and one from right to left, while keeping track of the number of open and close parentheses using two counters: open and close.

Why there is a Two Traversals?

  • Left to right traversal ensures that every valid substring that ends at the rightmost closing parenthesis is counted.
  • Right to left traversal ensures that every valid substring that starts from the leftmost opening parenthesis is counted.

Follow the steps below to solve the problem:

  • Left to Right Traversal:
    • Use two counters, say open to count the number of opening parentheses ‘(‘, and close to count the number of closing parentheses ‘)’.
    • For each character, if it’s ‘(‘, increment open else increment close.
    • Whenever open == close, we have found a valid substring, and we calculate the length: 2 * close. Keep track of the maximum valid length.
    • If at any point close exceeds open, it means we have too many closing parentheses, and we reset both open and close to 0.
  • Right to Left Traversal:
    • Similarly, use open and close counters again.
    • For each character, if it’s ‘(‘, increment open else increment close.
    • Again, whenever open == close, update the maximum valid length.
    • If open exceeds close, reset both counters to 0.

Below is the implementation of the above algorithm. 

C++
// C++ program to find length of the
// longest valid substring

#include <bits/stdc++.h>
using namespace std;

int maxLength(string s) {
    int maxLen = 0;

    // Left to Right Traversal
    int open = 0, close = 0;
    for (char ch : s) {
        if (ch == '(') {
            open++;
        }
        else if (ch == ')') {
            close++;
        }

        if (open == close) {
            maxLen = max(maxLen, 2 * close);
        }
        else if (close > open) {
            open = close = 0;
        }
    }

    // Right to Left Traversal
    open = close = 0;
    for (int i = s.size() - 1; i >= 0; i--) {
        if (s[i] == '(') {
            open++;
        }
        else if (s[i] == ')') {
            close++;
        }

        if (open == close) {
            maxLen = max(maxLen, 2 * open);
        }
        else if (open > close) {
            open = close = 0;
        }
    }

    return maxLen;
}

int main(){
    string s = ")()())";
    cout << maxLength(s) << endl;
    return 0;
}
C
// C program to find length of the 
// longest valid substring 

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

int maxLength(char s[]) {
    int maxLen = 0;
    
    // Left to Right Traversal
    int open = 0, close = 0;
    int len = strlen(s);
    for (int i = 0; i < len; i++) {
        if (s[i] == '(') {
            open++;
        } else if (s[i] == ')') {
            close++;
        }

        if (open == close) {
            maxLen = (maxLen > 2 * close) ? maxLen : 2 * close;
        } else if (close > open) {
            open = close = 0;
        }
    }

    // Right to Left Traversal
    open = close = 0;
    for (int i = len - 1; i >= 0; i--) {
        if (s[i] == '(') {
            open++;
        } else if (s[i] == ')') {
            close++;
        }

        if (open == close) {
            maxLen = (maxLen > 2 * open) ? maxLen : 2 * open;
        } else if (open > close) {
            open = close = 0;
        }
    }

    return maxLen;
}

int main() {
    char s[] = ")()())";
    printf("%d\n", maxLength(s));
    return 0;
}
Java
// Java program to find length of the 
// longest valid substring 

class GfG {
    static int maxLength(String s) {
        int maxLen = 0;
        
        // Left to Right Traversal
        int open = 0, close = 0;
        for (char ch : s.toCharArray()) {
            if (ch == '(') {
                open++;
            } else if (ch == ')') {
                close++;
            }

            if (open == close) {
                maxLen = Math.max(maxLen, 2 * close);
            } else if (close > open) {
                open = close = 0;
            }
        }

        // Right to Left Traversal
        open = close = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == '(') {
                open++;
            } else if (s.charAt(i) == ')') {
                close++;
            }

            if (open == close) {
                maxLen = Math.max(maxLen, 2 * open);
            } else if (open > close) {
                open = close = 0;
            }
        }

        return maxLen;
    }

    public static void main(String[] args) {
        String s = ")()())";
        System.out.println(maxLength(s));
    }
}
Python
# Python program to find length of the 
# longest valid substring 

def maxLength(s):
    max_len = 0
    
    # Left to Right Traversal
    open = close = 0
    for ch in s:
        if ch == '(':
            open += 1
        elif ch == ')':
            close += 1
        
        if open == close:
            max_len = max(max_len, 2 * close)
        elif close > open:
            open = close = 0
    
    # Right to Left Traversal
    open = close = 0
    for ch in reversed(s):
        if ch == '(':
            open += 1
        elif ch == ')':
            close += 1
        
        if open == close:
            max_len = max(max_len, 2 * open)
        elif open > close:
            open = close = 0
    
    return max_len

if __name__ == "__main__":
    s = ")()())"
    print(maxLength(s))
C#
// C# program to find length of the 
// longest valid substring 

using System;

class GfG {
    static int MaxLength(string s) {
        int maxLen = 0;
        
        // Left to Right Traversal
        int open = 0, close = 0;
        foreach (char ch in s) {
            if (ch == '(') {
                open++;
            } else if (ch == ')') {
                close++;
            }

            if (open == close) {
                maxLen = Math.Max(maxLen, 2 * close);
            } else if (close > open) {
                open = close = 0;
            }
        }

        // Right to Left Traversal
        open = close = 0;
        for (int i = s.Length - 1; i >= 0; i--) {
            if (s[i] == '(') {
                open++;
            } else if (s[i] == ')') {
                close++;
            }

            if (open == close) {
                maxLen = Math.Max(maxLen, 2 * open);
            } else if (open > close) {
                open = close = 0;
            }
        }

        return maxLen;
    }

    static void Main(string[] args) {
        string s = ")()())";
        Console.WriteLine(MaxLength(s));
    }
}
JavaScript
// JavaScript program to find length of the 
// longest valid substring 

function maxLength(s) {
    let maxLen = 0;
    
    // Left to Right Traversal
    let open = 0, close = 0;
    for (let i = 0; i < s.length; i++) {
        if (s[i] === '(') {
            open++;
        } else if (s[i] === ')') {
            close++;
        }

        if (open === close) {
            maxLen = Math.max(maxLen, 2 * close);
        } else if (close > open) {
            open = close = 0;
        }
    }

    // Right to Left Traversal
    open = close = 0;
    for (let i = s.length - 1; i >= 0; i--) {
        if (s[i] === '(') {
            open++;
        } else if (s[i] === ')') {
            close++;
        }

        if (open === close) {
            maxLen = Math.max(maxLen, 2 * open);
        } else if (open > close) {
            open = close = 0;
        }
    }

    return maxLen;
}

const s = ")()())";
console.log(maxLength(s));

Output
4

Time Complexity: O(n), where n is the size of string.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Count pairs of parentheses sequences such that parentheses are balanced
Given N bracket sequences, the task is to find the number of pairs of bracket sequences by joining which can be obtained a balanced bracket sequence as a whole. A bracket parentheses sequence can only be a part of a single pair. Examples: Input: { ")())", ")", "((", "((", "(", ")", ")"} Output: 2 Bracket sequence {1, 3} and {5, 6} Input: {"()", "((
9 min read
Minimum number of Parentheses to be added to make it valid
Given a string S of parentheses '(' or ')' where, [Tex]0\leq len(S)\leq 1000 [/Tex]. The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: str = "(((" Output: 3 Three ')' is requi
9 min read
Find the number of valid parentheses expressions of given length
Given a number n find the number of valid parentheses expressions of that length. Examples : Input: 2 Output: 1 There is only possible valid expression of length 2, "()" Input: 4 Output: 2 Possible valid expression of length 4 are "(())" and "()()" Input: 6 Output: 5 Possible valid expressions are ((())), ()(()), ()()(), (())() and (()()) This is m
9 min read
Valid Parentheses in an Expression
Given an expression string s, write a program to examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in the given expression. Example: Input: s = "[()]{}{[()()]()}" Output: trueExplanation: All the brackets are well-formed Input: s = "[(])" Output: falseExplanation: 1 and 4 brackets are not balanced because there is
9 min read
Reduce string by removing outermost parentheses from each primitive substring
Given a string S of valid parentheses "(" and ")", the task is to print the string obtained by removing the outermost parentheses of every primitive substring from S. A valid parentheses substring S is primitive if it is non-empty, and cannot be split into two or more non-empty substrings which are also a valid parentheses. Examples: Input: S = "((
9 min read
Length of longest balanced parentheses prefix
Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6 The idea is take value of open bracket '(' as 1 and value of close bracket ')
9 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Longest Substring of A that can be changed to Substring of B in at most T cost
Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. Note: If multiple valid substrings are possible then
13 min read
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string. Note: There can be more than one valid sequence, print any of them. Examples: Input: S = "()()()", K = 4Output: ()()Explanation:The string "()()" is a subse
7 min read
Check valid Substring of at least k length
Given a string s ('a' <= s[i] <= 'z') and an integer k (1 <= k < n <= 105), the task is to check if any valid substrings of at least k length exist in the given string. A substring is valid if the occurrences of each character in the substring should be even. Examples: Input: s = “bba”, k = 2Output: trueExplanation: Below is valid su
5 min read
Count Valid Substring of paranthesis with at max K consecutive same characters
Given an integer K, a string S of length N, consisting of '(' or ')' or '?' characters. We can replace each '?' character with either '(' or ')' character. The task is to find the total number of unique valid strings you can generate such that the maximum length of the substring containing the same characters is no more than K.A valid string is a s
13 min read
Find the length of the longest valid number chain in an Array
Given an array A[] of N numbers, the task is to find the length of the longest valid number that can be formed by connecting one or more numbers from the array such that, while connecting two numbers the last digit of the previous number is the same as the first digit of the next number. Examples: Input: A = [100, 234, 416, 654, 412, 298, 820, 177]
10 min read
Longest Valid Word with All Prefixes
Given an array of N strings words[]. Find longest string in words[] such that such that every prefix of it is also in words[]. If there are multiple answers print the lexicographically shortest string. Examples: Input: words = {"a" , "banana" , "app" , "apply" , "ap" , "appl" , "apple"}Output: apple Explanation: For the first string "a", only prefi
14 min read
Pairs involved in Balanced Parentheses
Given a string of brackets, the task is to find the number of pairs of brackets involved in a balanced sequence in a given range. Examples : Input : ((())(() Range : 1 5 Range : 3 8 Output : 2 2 Explanation : In range 1 to 5 ((()), there are the two pairs. In range 3 to 8 ()) ((), there are the two pairs. Input : )()())) Range : 1 2 Range : 4 7 Out
14 min read
Cost to Balance the parentheses
Parentheses are said to be balanced when every opening brace has a closing brace like "()()" or "(())" or "(()())" etc. Incorrect balancing includes ")(" or "))((" etc. The task here is to correct the sequence of parentheses in such a way that it is done in minimum cost. And shifting of parentheses by over one parentheses costs 1. If the parenthese
7 min read
Check for balanced parentheses in an expression | O(1) space
Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed to use only O(1) extra space. Also See : Check for balanced parentheses Examples: Input : (())[] Output : Yes Input : ))(({}{ Output : No If k = 1, then we will
15+ min read
Number of balanced parentheses substrings
Given a balanced parentheses string which consists of '(' and ')'. The task is to find the number of balanced parentheses substrings in the given string Examples : Input : str = "()()()" Output : 6 (), (), (), ()(), ()(), ()()()Input : str = "(())()" Output : 4 (), (()), (), (())() Approach : Let us assume that whenever we encounter with opening br
6 min read
Number of ways to insert two pairs of parentheses into a string of N characters
Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.Examples: Input: str = "ab" Output: 6 ((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b)) which are a total of 6 ways.Input: str = "aab" Output: 20 Approach: it can be observed t
3 min read
Check if the Depth of Parentheses is correct in the given String
Given a string S consisting of opening parentheses, closing parentheses and integers, the task is to print Yes if, in this string, the integers correctly indicates its depth. Depth refers to the number of nested sets of parentheses surrounding that integer. Print No otherwise.Examples: Input: S = "((2)((3)))" Output: Yes Explanation: No of Opening
7 min read
Insert minimum parentheses to make string balanced
Given a string of digits S. The task is to insert a minimum number of opening and closing parentheses into the string S such that the resulting string is balanced and each digit d must be inside d pairs of matching parentheses. Examples: Input: S = 221 Output: ((22)1) Explanation: The string ((2))((2))(1) is not valid solutions because it is not of
6 min read
Balance the parentheses for the given number N
Given a number N, the task is to insert the minimum number of opening and closing parenthesis into the number N such that the resultant string is balanced and every digit D is exactly in D pairs of matching parenthesis. Examples: Input: N = 312 Output: (((3))1(2)) Explanation: Every digit in the number is within exactly in D parenthesis. There are
3 min read
Print the string obtained after removal of outermost parentheses
Given a valid parenthesis string str consisting of lowercase alphabets, opening, and closing brackets, the task is to find the string by removing the outermost enclosing brackets such that the string remains a valid parenthesis string. Examples: Input: S = "(((a)(bcd)(e)))"Output: (a)(bcd)(e)Explanation: The outermost enclosing brackets are: { S[0]
8 min read
Calculate score of a string consisting of balanced parentheses
Given a string str consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the following rules: "()" has a score of 1."x y" has a score of x + y where x and y are individual pairs of balanced parentheses."(x)" has a score twice of x (i.e), 2 * score of x. Examples: Input: str = "()()"Output: 2Exp
7 min read
Number of levels having balanced parentheses in a Binary Tree
Given a Binary Tree consisting only '(' and ')' a level is considered to be balanced if the nodes of the level having parenthesis are balanced from left to right. The task is to count the total number of balanced levels in a binary tree. Examples: Input: ( / \ ( ) / \ \ ( ) ( / \ \ \ ( ( ) ) Output: 2Explanation:In Level 2 and 4, the parenthesis ar
10 min read
Calculate score of parentheses from a given string
Given string str of length N, consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules: “()” has a score of 1.“a b” has a score of a + b, where a and b are individual pairs of balanced parentheses.“(a)” has a score twice of a i.e., the score is 2 * score of a. Examples: Input: str
6 min read
Arrange given numbers in a mathematical expression using operators [+, -, *, /] and parentheses to get value 24
Given an array arr[] consisting of 4 integers each between [1-9], the task is to check whether it is possible to get the number 24 by placing the operators +, -, /, and * between the numbers or grouping them using parenthesis. If it is possible then print "Possible", Otherwise print "Not Possible". Examples: Input: arr[] = {3, 6, 8, 2}Output: Possi
11 min read
Modify a numeric string to a balanced parentheses by replacements
Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the same parentheses. Examples: Input: S = "1123"Outpu
10 min read
Remove Invalid Parentheses
An expression will be given which can contain open and close parentheses and optionally some characters, No other operator will be there in string. We need to remove minimum number of parentheses to make the input string valid. If more than one valid output are possible removing same number of parentheses then print all such output. Examples: Input
9 min read
Print all combinations of balanced parentheses
Given a number n, the task is to generate all possible n pairs of balanced parentheses. Examples: Input: n=1Output: {}Explanation: This the only sequence of balanced parenthesis formed using 1 pair of balanced parenthesis. Input : n=2Output: {}{} {{}}Explanation: This the only two sequences of balanced parenthesis formed using 2 pair of balanced pa
12 min read
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'nd substring. Examples: Input : "11235813" Output : ["1", "1", "2", "3", "5", "8", "13"] Input : "1111223" Output : ["1", "11", "12", "23"] Input : "1111213" Output : ["11", "1", "12", "13"] Input : "11121114" Output : []Iterate through the given string by pickin
9 min read