diff --git a/Domains/CompetitiveProgramming/Programs/Java/ExpressionBalancer/ExpressionBalancer.java b/Domains/CompetitiveProgramming/Programs/Java/ExpressionBalancer/ExpressionBalancer.java new file mode 100644 index 00000000..c70f568a --- /dev/null +++ b/Domains/CompetitiveProgramming/Programs/Java/ExpressionBalancer/ExpressionBalancer.java @@ -0,0 +1,43 @@ +import java.util.Stack; +import java.util.Scanner; + +public class ExpressionBalancer { + public static boolean isBalanced(String expr) { + Stack stack = new Stack<>(); + + for (char ch : expr.toCharArray()) { + // Push opening brackets + if (ch == '(' || ch == '{' || ch == '[') { + stack.push(ch); + } + // Check closing brackets + else if (ch == ')' || ch == '}' || ch == ']') { + if (stack.isEmpty()) return false; + char top = stack.pop(); + + if ((ch == ')' && top != '(') || + (ch == '}' && top != '{') || + (ch == ']' && top != '[')) { + return false; + } + } + } + + // Stack must be empty for balanced expression + return stack.isEmpty(); + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("===== EXPRESSION BALANCER ====="); + System.out.print("Enter an expression: "); + String expr = sc.nextLine(); + + if (isBalanced(expr)) + System.out.println("✅ Expression is Balanced!"); + else + System.out.println("❌ Expression is NOT Balanced!"); + + sc.close(); + } +} diff --git a/Domains/CompetitiveProgramming/Programs/Java/ExpressionBalancer/README.md b/Domains/CompetitiveProgramming/Programs/Java/ExpressionBalancer/README.md new file mode 100644 index 00000000..4bfe471e --- /dev/null +++ b/Domains/CompetitiveProgramming/Programs/Java/ExpressionBalancer/README.md @@ -0,0 +1,40 @@ +**Contributor** SOSWAL007 +# Expression Balancer + +A simple Java program that checks whether a given mathematical or logical expression has balanced parentheses, curly braces, and square brackets using a Stack data structure. + +--- + +### Project Overview + +This program verifies if the brackets in an expression are properly opened and closed in the correct order. +It supports: +- Round brackets () +- Curly brackets {} +- Square brackets [] + +The implementation uses Java’s built-in `Stack` class to push opening brackets and pop them when matching closing brackets appear. + +--- + +### Features + +- Checks for balanced brackets in any given string +- Supports multiple types of brackets +- Uses Stack — a core Data Structure concept +- Simple command-line input/output +- Beginner-friendly and easy to understand + +--- + +### Working Principle + +1. Traverse each character of the input expression. +2. If the character is an opening bracket — push it to the stack. +3. If the character is a closing bracket: + - Check if the stack is empty (if yes → unbalanced). + - Pop the top element and verify if it matches the type of closing bracket. + - If it doesn’t match → unbalanced. +4. After traversal, if the stack is empty → expression is balanced. + +