Valid Parentheses in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <string.h>

int isValid(char *s) {
    char stack[1000];
    int top = -1;
    for (int i = 0; s[i]; i++) {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
            stack[++top] = s[i];
        } else {
            if (top == -1) return 0;
            char c = stack[top--];
            if ((s[i] == ')' && c != '(') ||
                (s[i] == '}' && c != '{') ||
                (s[i] == ']' && c != '['))
                return 0;
        }
    }
    return top == -1;
}

int main() {
    char s[100];
    scanf("%s", s);
    if (isValid(s))
        printf("Valid\n");
    else
        printf("Invalid\n");
    return 0;
}

C Output

Input:  
{[()]}  

Output:  
Valid


C++ Program

#include <iostream>
#include <stack>
using namespace std;

bool isValid(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '{' || c == '[')
            st.push(c);
        else {
            if (st.empty()) return false;
            char t = st.top(); st.pop();
            if ((c == ')' && t != '(') ||
                (c == '}' && t != '{') ||
                (c == ']' && t != '['))
                return false;
        }
    }
    return st.empty();
}

int main() {
    string s;
    cin >> s;
    cout << (isValid(s) ? "Valid" : "Invalid") << endl;
}

C++ Output

Input:  
([)]

Output:  
Invalid


JAVA Program

import java.util.*;

public class Main {
    public static boolean isValid(String s) {
        Stack<Character> st = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[')
                st.push(c);
            else {
                if (st.isEmpty()) return false;
                char t = st.pop();
                if ((c == ')' && t != '(') ||
                    (c == '}' && t != '{') ||
                    (c == ']' && t != '['))
                    return false;
            }
        }
        return st.isEmpty();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        System.out.println(isValid(s) ? "Valid" : "Invalid");
    }
}

JAVA Output

Input:  
((()))  

Output:  
Valid


Python Program

def isValid(s: str) -> bool:
    stack = []
    mapping = {')':'(', '}':'{', ']':'['}
    for c in s:
        if c in "({[":
            stack.append(c)
        else:
            if not stack or stack[-1] != mapping[c]:
                return False
            stack.pop()
    return not stack

s = input()
print("Valid" if isValid(s) else "Invalid")

Python Output

Input:  
((]{})

Output:  
Invalid


Detailed Explanation
Sample
Consider the string {[()]}. Whenever we read each character, every opening bracket {, [, ( is pushed onto a stack. Whenever we read a closing bracket ), we compare the top of the stack with it. If it matches, we pop it off the stack. At the end, if the stack is empty, it means that everything was correctly matched, so "Valid". If ever there is a mismatch or something left open, it is "Invalid".

Real-Life Analogy
Suppose you have boxes stacked within larger boxes. When you open a big box and insert a medium box, followed by a small box, you need to close them in the opposite order: close the small first, medium second, and big third. If you attempt to close a big box while the smaller ones remain open within, the packing is defective. That is what parenthesis validation does—last opened should be first closed.

Why It Matters
Balanced parentheses checking is an important computer science problem as it is an example introducing the idea of stacks. Stacks are based on the Last-In-First-Out (LIFO) principle, which is important in memory management, undo-redo, parsing expressions, compiler design, and even in real systems such as nested task tracking. Without balanced parentheses, programs may get erroneous mathematical expressions or may not compile.

Learning Insights
This exercise educates beginners how to represent real-world nested structures using stacks. It highlights the significance of ordering in programming—what is added last has to be removed first. It demonstrates how mapping (such as ) → () makes it easy to check conditions. This sets students up for more challenging problems such as evaluating arithmetic expressions, HTML/XML tag checking, and recursive parsing. 

Interview Use Case
"Valid Parentheses" ranks among the top commonly asked coding interview questions since it tests a candidate's skill in utilizing stacks, corner cases, and nesting. Interviewers also enjoy asking to validate HTML/XML tags or arithmetic expressions to make this case more challenging, so getting to know this problem is a great way to establish a strong background in harder challenges.

SEO-Optimized Closing
The valid parentheses is a traditional stack-based coding challenge that all beginners and interview candidates need to practice. Learning to validate balanced brackets in C, C++, Java, and Python helps you understand stack operations, parsing expressions, and compiler principles. If you're preparing for coding interviews, practicing data structures, or developing real-world applications where you need expression validation, the technique of checking valid parentheses will enhance your problem-solving ability and coding skills considerably.