• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Closed Parentheses checker

December 26, 2017 by Dhaval Dave

‏Problem Statement:

You are given 3 types of parentheses (),{},[]. Now you are supposed to check whether a given string containing some parentheses is closed or not.

example depicting closed sequence

Now there is a twist. Instead of checking whether a complete sequence is closed or not, you will be given a incomplete sequence containing a ‘X’ indicating a empty space and then you will have to output whether a closed sequence is possible or not.

example explaining problem

NOTE – There will at most 5 ‘X’ in a sequence and sequence can be of at most 10000.

Required Knowledge:

Backtracking

Time Complexity:

O(n*6(# of ‘X’))

 

Solution:

Here the important thing to note is that running time depends on no. of X which as defined in the question is at most 5. So we can use backtracking to solve this problem.

Now, let us see how we will apply backtracking in solving this parenthesis problem. First we will define the the base and recursion for backtracking.

The base condition is if it the sequence contains no ‘X’ then we will check whether the sequence is closed or not using the check function whose functioning we will discuss later.

The recursive condition is that we will replace each ‘X’ with one of the six parenthesis and then continue with the recursion.

Now let us discuss the functioning of the check functioning. In the check function, if the parenthesis is a left one, then we push a unique number corresponding to 3 pair of parentheses in a stack. If it is a right one, then we check whether the stack is empty or not. If it is empty then it is sure shot that it is impossible to form a closed sequence. Now if it is not, then there still remains a possibility. Now we check whether its corresponding left exists as top or not. If it exists then we continue or we return false.

 

Now,let us see working for an example.

example for working

(i) For the first one

first case(ii) For the second case

third case(iii) For the third case

third case

After this we stop, since we have already confirmed there is a closed sequence possible from the given incomplete sequence.

Code

Implemented in C++

#include <bits/stdc++.h>
using namespace std;

bool check(string s){                       // This function is used to check a parenthesis sequence 
  stack<int > st;                           // is closed or not
                                            // The idea behind this function is:
  for(int i=0;i<s.length();i++){            // 1. if it's left parenthesis, then push it
    if(s[i]=='{')				// 2. it it's right parenthesis, then check if its 
      st.push(1);				//    corresponding left occurs or not. if not then return
    else if(s[i]=='[')			//    false or else continue
      st.push(2);
    else if(s[i]=='(')
      st.push(3);
    else if(s[i]==')'){
      if(st.empty())
        return false;
      int t=st.top();
      //cout<<t<<endl;
      if(t==3){
        st.pop();
        if(st.empty())st.push(0);
      }
      else
        return false;
    }
    else if(s[i]==']'){
      if(st.empty())
        return false;
      int t=st.top();
      //cout<<t<<endl;
      if(t==2){
        st.pop();
        if(st.empty())st.push(0);
      }
      else
        return false;
    }
    else{
      if(st.empty())
        return false;
      int t=st.top();
      //cout<<t<<endl;
      if(t==1){
        st.pop();
        if(st.empty())st.push(0);
      }
      else
        return false;
    }
  }

  while(!st.empty()){
    int t=st.top();
    if(t!=0)
      return false;
    st.pop();
  }
  return true;
}

bool ans=false;				// This is a global var which contains true/false
char possible[]={'{','[','(',')',']','}'};		// This contains all possible parentheses

void rec(string s,int k,int x){			// This recursion is defined as following:
	if(ans)return;
	if(x==0){				// 1. Base case: if x=0 then check for closed
		if(ans==true)return;							
		ans=check(s);
		return;
	}
	for(int i=k;i<s.length();i++){		// 2. Recursion: change a 'X' to a parenthesis
		if(s[i]=='X'){			//    then check for the rest
			for(int j=0;j<6;j++){ 
                                s[i]=possible[j]; 
                                rec(s,i+1,x-1); 
                        } 
                } 
        } 
} 

int main(){ 
  string s; 
  cin>>s;
  int x=0;
  for(int i=0;i<s.length();i++)if(s[i]=='X')x++;
  rec(s,0,x);
  (ans==1)?cout<<"Possible\n":cout<<"Impossible\n";
  return 0;
}

 

This Article is Published by Arnab Ghosh.
If you want to be a content writer with Gohired.in, please write at career@gohired.in or at admin@gohired.in.

 

Similar Articles

Filed Under: Amazon Interview Question, Interview Questions Tagged With: algorithm, backtracking

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Search element in a matrix with all rows and columns in sorted order

LeetCode: Binary Tree Maximum Path Sum

Given array of 0’s and 1’s. All 0’s are coming first followed by 1’s. find the position of first 1

Print vertical sum of all the axis in the given binary tree

VMWare Openings

Find two non repeating elements in an array of repeating elements

In Given LinkedList Divide LL in N Sub parts and delete first K nodes of each part

Stock Buy Sell to Maximize Profit

Binary Tree in Java

Find the smallest window in a string containing all characters of another string

There are N nuts and N bolts, u have to find all the pairs of nuts and bolts in minimum no. of iteration

Given a sorted array and a number x, find the pair in array whose sum is closest to x

Minimum insertions to form a palindrome

Inorder and Preorder traversals of a Binary Tree given. Output the Postorder traversal of it.

Implement LRU Cache

Possible sizes of bus to carry n groups of friends

Number of Islands BFS/DFS

VMWare SDEII Interview

Handle duplicates in Binary Search Tree

Adobe Interview Questions 8 month Exp

Given Set of words or A String find whether chain is possible from these words or not

Top 10 Interviews Techniqes for Campus Interview in IIT NIT BITS for MTech

How Radix sort works

Max Sum in circularly situated Values

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Count number of ways to reach a given score in a game

Printing each word reverse in string

Calculate price of parking from parking start end time prices

Memory Efficient LinkedList

Subset Sum Problem Dynamic programming

Copyright © 2025 · Genesis Framework · WordPress · Log in