Balanced Sequence After Replacement

You are given a string of length ‘N’ containing only the following characters: ‘[’, ‘{’, ‘(’, ‘)’, ‘}’, ‘]’. At some places, there is ‘X’ in place of any bracket. Your task is to determine that if you replace all the X’s with appropriate brackets, is it possible to get a valid balanced sequence or not.

For example:

For the given string “[X)](X”, the possible replacement for the first X is ‘(‘ and the second X is ‘)’, which makes the sequence “[()]()”, which is a valid balanced sequence. 

For the given string “[XX{”, there is no possible replacement for X which can make it a valid bracket sequence.  
Input format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.

The first and only line of each test case or query contains the string. 
Output format:
For each test case, print “Valid” if a balanced sequence is possible, otherwise, print “Invalid”, without quotes in a separate line.

Note:

You do not need to print anything, it has already been taken care of. Just return 'True' for valid string and 'False' for an invalid string.
Constraints:
1 <= T <= 10 
1 <= N <= 20 

Time limit: 1 sec
CodingNinjas
author
2y
Using Recursion

The idea is to use stack data structure and is pretty much similar to the algorithm where we check if the expression is balanced or not.

We mainly have 3 conditions to fulfil i.e.

  1. Open...read more
Help your peers!
Add answer anonymously...
Veritas Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter