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

3917. Count Indices With Opposite Parity (Brute Force) O(n2) + Optimized Solution O(n) + tips LEETCODE WEEKLY 500

  class Solution {     public int [] countOppositeParity ( int [] nums ) {          // approach 1 - checks every pair         int n = n...