Check whether an expression includes an expression wrapped in duplicate parentheses, using a stack

I am to write a function for the following:

Given a balanced expression, find if it contains duplicate parenthesis or not. A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis.

For example, “((a+b)+((c+d)))” has duplicate parentheses around “c+d”.

My code:

import java.util.Stack;

public class DuplicateParentheses {
    public static boolean isduplicate(String str){
        Stack<Character> s = new Stack<>();
        for(int i =0 ; i<str.length() ; i++){
            char curr = str.charAt(i);
            if(curr == ')'){
                int count = 0;
                while(s.peek() != '('){
                    s.pop();
                    count++;
                    }
                s.pop();
                if(count==0){
                    return true;
                }
            }else{
                s.push(curr);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        String str = "((a+b)(+)(c+d))";
        System.out.println(isduplicate(str));
    }
}

It returns the wrong result for the following input: “((a+b)(c+d))”

The output should be false, but my code is returning true.

According to the logic of my code I expected it to return a correct result. What is the mistake?

New contributor

Tanush Garg is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Your code does not check whether there are two consecutive closing parentheses before it performs return true. Secondly, checking whether the count of non-opening parentheses you pop from the stack is zero is not a sound indication that there were two consecutive opening parentheses that relate to the last two closing parentheses.

My guess is you got this algorithm from reading the GeeksforGeeks article Find if an expression has duplicate parenthesis or not. But they provide a faulty algorithm as you have demonstrated with your input example (your Java code looks very similar to theirs).

Another algorithm

Here is another approach:

  • Use the stack to push the indices of where you have found opening parentheses. Don’t push anything else.

  • When encountering a closing parenthesis, read that index from the top of the stack, and then you have the two indices of the paired parentheses. Now it is a piece of cake to see if that pair is immediately wrapped by another pair of parentheses by just checking directly in the string at those “widened” indices.

Suggested code:

    public static boolean isduplicate(String str){
        Stack<Integer> s = new Stack<>(); // A stack of indices
        int n = str.length();
        for (int i = 0; i < n; i++) {
            char curr = str.charAt(i);
            if (curr == ')') {
                int j = s.peek(); // Get index of matching '('
                s.pop();
                // If the pair is wrapped in another pair of parentheses:
                if (j > 0 && str.charAt(j-1) == '(' && str.charAt(i+1) == ')') {
                    return true; // ...then we have a duplicated pair
                }
            } else {
                s.push(i); // Push the index
            }
        }
        return false;
    }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật