GoldmanSachs

Cracking Goldman Sachs Interview: Finding the Longest Valid Parentheses in Java


You have given a string that contains the braces (brackets), both opening and closing braces. You have to find the length of the Longest Valid Parentheses.


Input : {}{}{()[]()
Output: 6
Input : {}{}{()[](){}{}]]{}[]
Output: 10
Input : {}{}(){}(){()[]()
Output: 10

Longest Valid Parentheses

https://leetcode.com/problems/longest-valid-parentheses/
Java
import java.util.*;
public class LongestValidParentheses {
    public static void main(String[] args) {
        String str1 = "{}{}{()[]()";
        String str2 = "{}{}{()[](){}{}]]{}[]";
        String str3 = "{}{}(){}(){()[]()";
        System.out.println("Length of longest balanced subarray in '" + str1 + "' is: " + longestValidParentheses(str1));
        System.out.println("Length of longest balanced subarray in '" + str2 + "' is: " + longestValidParentheses(str2));
        System.out.println("Length of longest balanced subarray in '" + str3 + "' is: " + longestValidParentheses(str3));
    }
    public static int longestValidParentheses(String s) {
        int maxLength =0;
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        for(int i=0; i< s.length(); i++){
            char parentheses = s.charAt(i);
            if( parentheses == '(' || parentheses == '[' || parentheses == '{' ){
                stack.push(i);
            }else{
                if(stack.isEmpty() || stack.peek() != -1 && !matchingParentheses(s.charAt(stack.peek()), parentheses )){
                    stack.push(i);
                }else{
                    stack.pop();
                    if(stack.isEmpty()){
                        stack.push(i);
                    }else{
                        maxLength = Math.max(maxLength, i- stack.peek() );
                    }

                }
            }
        }
        return maxLength;
    }
    public static boolean matchingParentheses(char left, char right){
        if ( (left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}') ){
            return true;
        }
        return false;

    }
}

Check the running code on https://leetcode.com/playground/39L6d2BS

Avatar

Neelabh

About Author

As Neelabh Singh, I am a Senior Software Engineer with 6.6 years of experience, specializing in Java technologies, Microservices, AWS, Algorithms, and Data Structures. I am also a technology blogger and an active participant in several online coding communities.

You may also like

Blog Algorithm Data Structure GoldmanSachs

Conquering the GS Interview 💼: Transforming Fractions to Decimals and Cyclic Patterns 📝

🤔 The Challenge: Fractions to Decimals In the world of mathematics, fractions are a fundamental concept that represents the division
Blog GoldmanSachs Interview Experiences

📚 Best Average Grade Solution in Java 💯

Best Average Grade Are you preparing for coding interviews at top companies like Goldman Sachs? 💼 One of the popular