View profile

DS Weekly - Find whether the given expression is balanced

Revue
 
 

DS Weekly

October 31 · Issue #1 · View online
Learning data-structures and algorithms need commitment. I'm gonna make it easier by sending you a solved programming challenge weekly from a curated collection of data-structures, algorithms, competitive programming questions, interview questions straight to your mailbox.

Problem Statement
Given an expression. Write a program to check whether the given expression is balanced or not.
Sample Input:
{ [ ( ) ] }
Output:
True
Sample Input - 2
{ [ } ]
Output:
False
Sample Input - 3
{ { [ ]
Output
False

Try to solve the problem in O(n) before looking into the solution

Solution:
This problem is so simple. For every opening brackets, you have to check whether the corresponding closing brackets are present in order. 
We can solve this problem using Stack. If you want a recap about stack no problem take a look at this.
First, we start by iterating through the string and if we find an opening bracket we push it to the stack. And if we find a closing bracket we are popping the top element from the stack to check whether the closing bracket is associated with the opening bracket (top element popped). If not, we are returning false or else we continue. 
And remember after iterating through the entire string, we have to check the size of the stack. If the size of the stack is not zero (i.e) not empty it means that some closing brackets are missing. 
If you don’t get it stay with me :)
Pseudocode
Balanced Expression pseudo code
Balanced Expression pseudo code
Java
Java implementation of BalancedExpression
Java implementation of BalancedExpression
Here’s the link to the source code and to the pseudo code

If you got any feedback or anything you can reply to this email. 
Thank you for reading this issue. :) :) 
If you think this is helpful don’t mind to share it :) :)
Did you enjoy this issue?
If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue