Sie sind auf Seite 1von 7

Custom Search Write an Article Login

Algo ▼ DS ▼ Languages ▼ Interview ▼ Students ▼ GATE ▼ CS Subjects ▼ Quizzes ▼ GBlog Puzzles

What’s New?

Check for balanced parentheses in an

How to write an Interview

Must Do Coding Questions

Given an expression string exp , write a program to examine whether the
Must Do Coding Questions
Topic-wise pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. For example, the
program should print true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”
Difficulty Levels






Popular Tags

Amazon, Microsoft, Dynamic Recommended: Please solve it on “PRACTICE ” first, before

Programming, Samsung
moving on to the solution.
Click here for more

Interview Preparation Algorithm:

Step by Step Preparation 1) Declare a character stack S.
2) Now traverse the expression string exp.
Company Preparation
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to
Top Topics stack.

W eb page converted to PDF w ith the PDFmyURL PDF creation API!

Company Specific Practice
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from
stack and if the popped character is the matching starting bracket then fine Trending Content
Software Design Patterns else parenthesis are not balanced. Python List , Set , Tuple & Dictionary
3) After complete traversal, if there is some starting bracket left in stack then Number Theory
Placements Preparation
Course “not balanced” Set to Array in Java

Interview Corner Implementation: BFS , DFS

School Programming
Recent Interview
Experiences Longest Repeated Subsequence
C C++ Java Longest Palindromic Subsequence
GQ Home Page
Detect a negative cycle.
Quiz Corner
#include<stdio.h> GATE CS Notes
LMNs Reverse a linked list
#define bool int

Practice Platform /* structure of a stack node */

struct sNode
What's New ? {
char data;
struct sNode *next;
Leaderboard !! };

Topic-wise Practice /* Function to push an item to stack*/

void push(struct sNode** top_ref, int new_data);
Subjective Problems /* Function to pop an item from stack*/
int pop(struct sNode** top_ref);
Difficulty Level - School
/* Returns 1 if character1 and character2 are matching left
and right Parenthesis */
Difficulty Level - Basic
bool isMatchingPair(char character1, char character2)
Difficulty Level - Easy if (character1 == '(' && character2 == ')')
return 1;
Difficulty Level - Medium else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
Difficulty Level - Hard return 1;
How to pick a difficulty level? return 0;
Explore More... /*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
Programming Languages {
int i = 0;
W eb page converted to PDF w ith the PDFmyURL PDF creation API!
C /* Declare an empty character stack */
struct sNode *stack = NULL;
/* Traverse the given expression to check matching parenthesis */
while (exp[i])
Java {
/*If the exp[i] is a starting parenthesis then push it*/
Python if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
SQL /* If exp[i] is an ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
Important Quick Links if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
School Programming
/*If we see an ending parenthesis without a pair then return false*/
if (stack == NULL)
Operating Systems return 0;

DBMS /* Pop the top element from stack, if it is not a pair

parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
Computer Networks else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
Engineering Mathematics }
Design Patterns
/* If there is something left in expression then there is a starting
Common Interview Puzzles parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
Web Technology
return 0; /*not balanced*/
G-Facts }

Computer Graphics /* UTILITY FUNCTIONS */

/*driver program to test above functions*/
int main() Most Visited Posts
Image Processing {
char exp[100] = "{()}[]"; Top 10 Algorithms and Data Structures for
Project Ideas if (areParenthesisBalanced(exp)) Competitive Programming
printf("n Balanced ");
else Top 10 algorithms in Interview Questions
printf("n Not Balanced ");
return 0; How to begin with Competitive
/* Function to push an item to stack*/
Step by Step Guide for Placement
void push(struct sNode** top_ref, int new_data)
{ Preparation
/* allocate node */
struct sNode* new_node =
W eb page converted to PDF w ith the PDFmyURL PDF creation API!
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
Most Visited Posts
if (new_node == NULL)
How to prepare for ACM-ICPC?
printf("Stack overflow n"); Insertion Sort , Binary Search , QuickSort ,
exit(0); MergeSort , HeapSort

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = (*top_ref);

/* move the head to point to the new node */

(*top_ref) = new_node;

/* Function to pop an item from stack*/

int pop(struct sNode** top_ref)
char res;
struct sNode *top;

/*If stack is empty then error */

if (*top_ref == NULL)
printf("Stack overflow n");
top = *top_ref;
res = top->data;
*top_ref = top->next;
return res;

Run on IDE

Popular Categories
Interview Experiences
Advanced Data Structures

W eb page converted to PDF w ith the PDFmyURL PDF creation API!

Time Complexity: O(n) Popular Categories
Auxiliary Space: O(n) for stack. Dynamic Programming

Greedy Algorithms


Pattern Searching

Divide & Conquer

Geometric Algorithms



Analysis of Algorithms

Mathematical Algorithms

Randomized Algorithms


Game Theory

Statistical Algorithms
Advertise Here

Please write comments if you find any bug in above codes/algorithms, or find
other ways to solve the same problem
Advanced Data Structure Amazon
Aptitude Aptitude Arrays Bit
Magic C C C++ C++ Quiz CPP-
Library C Quiz Data Structures Dynamic
Stack Login to Improve this Article Programming Experienced GBlog
Geometric Graph Hash Internship
Please write to us at to report any issue with the above
Experiences Java
JavaScript Linked Lists
Recommended Posts: Mathematical Matrix
Microsoft number-digits PHP Program

Next Greater Element

Python QA -
Output Project Puzzles
Placement Quizzes QA - Placement
W eb page converted to PDF w ith the PDFmyURL PDF creation API!
Reverse a stack using recursion Quizzes School Programming
Stack | Set 2 (Infix to Postfix) Searching series Sorting STL
Stack Data Structure (Introduction and Program) Strings Technical Scripter Trees
UGC-NET Web Technologies
Implement two stacks in an array
Print Bracket Number Adve rtise He re
Prefix to Infix Conversion
Prefix to Postfix Conversion Recent Comments
Postfix to Prefix Conversion
Postfix to Infix

<< Previous Post Next Post >>

(Login to Rate)

1.9 Average Difficulty : 1.9/5.0

Based on 273 vote(s)
Add to TODO List
Mark as DONE
Basic Easy Medium Hard Expert

Writing code in comment? Please use, generate link and

share the link here.

Load Comments

Share this post!

W eb page converted to PDF w ith the PDFmyURL PDF creation API!

710-B, Advant Navis Business Park,
Sector-142, Noida, Uttar Pradesh - 201305


About Us Algorithms Company-wise Write an Article
Careers Data Structures Topic-wise GBlog
Privacy Policy Languages Contests Videos
Contact Us CS Subjects Subjective Questions
Video Tutorials

@geeksforgeeks, Some rights reserved

W eb page converted to PDF w ith the PDFmyURL PDF creation API!