Pages

Friday, September 26, 2025

Duplicate Parentheses - (V.V.imp) asked in Microsoft, Google! Stack question

 


import java.util.*;

public class Duplicate_parentheses {


    public static boolean isDuplicate(String str) {
        Stack<Character> s = new Stack<>();

        for(int i=0; i<str.length(); i++) {
            char ch = str.charAt(i);
           
           
            // closing
            if(ch == ')') {
                int count = 0;

                while(s.pop() != '(') {
                    count++;

                }
               
                if(count < 1) {
                    return true; // duplicate exists
                }

            } else {
                // opening
                s.push(ch);
            }
        }

        return false;

    }
    public static void main(String[] args) {
        String str = "((a+b))"; // true
        String str2 = "(a-b)"; // false
        System.out.println(isDuplicate(str));
        System.out.println(isDuplicate(str2));

    }
   
}
OUTPUT: true false

No comments:

Post a Comment

3Sum - Leetcode solution - How i turned into two-pointer approach?

  class Solution {     public List < List < Integer >> threeSum ( int [] nums ) {         Arrays . sort (nums); // first sort...