Microsoft Interview Question


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
10
of 10 vote

use a stack and push left brace (3 types ) whenever u encounter on to stack.
for every right braces you encounter check if stack is empty or not matching the top of the stack , if so return false else pop the top.

continue. like this till you traverse the whole string.

Afterwards, just check if stack is empty or not and accordingly return true or false.

- foobar December 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why this is voted -ve? This will ensure the parenthesis are proper, right?

- Anonymous December 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Stack is the perfect solution

- kartykkeyan December 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

the algo won't work for {([}]) right?

- Anonymous December 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is the most appropriate solution for parenthesis problem,
doesn't matter whether you use more than 1 parenthesis.

- Ankit Tripathi December 31, 2012 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Stack is not advised as it will consume more space. Suppose if we have a string which begins with 1000 '('characters, the stack will go to a depth of 1000.
A more efficient way is to maintain a parenthesis counter and a last parenthesis variable.
Correct me if I am wrong.

- IAmIronMan July 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

{([}]) is not a right test cae

@IAmIronMan You cannot maintain a last_parantheses variable. Suppose your expression is { ( [ ] ) }
after [ your last parantheses will be [ . When you see ] you can check that this is fine. But what will you reinitialize last parantheses to after this step?

- Sugarcane_farmer May 15, 2014 | Flag
Comment hidden because of low score. Click to expand.
2
of 6 vote

Add a 1 for startBracket and -1 for endBracket. As soon as number goes negative, you can declare string as unbalanced. One more condition is that at-last, sum should be 0.

- Anonymous December 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

i think you will be failed in the simple case of ")("? the result is 0.

I will do it with a stack. push one in while we met a left bracket, and pop one out while we met a right bracket, and when it throws an exception that the stack is empty and can't be popped out or while in the end there are still objects in that stack, we know it's unbalanced.

- Anonymous December 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

No, the logic works. The failure happens at the very first character in your example as the total would be -1. Read carefully his logic: 'as soon as'. He did not say to wait till the end.

Thanks,
Laxmi

- Laxmi Narsimha Rao Oruganti December 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Still, {([}]) is not a proper parenthesis, right?

- Anonymous December 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

For more than 1 parenthesis, one must use a stack

- Ankit Tripathi December 31, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

it will work for this instance-{([}]).While popping just match the current input with top of stack .

- Vikash January 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

This will work perfectly with single parens if you

return false

if the count goes negative at any time. Plus if you have a

char prev='\0'

having the previous paren you can match any closing paren with the corresponding prev counterpart and return false if violation occur.

- citpyrc January 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript code:

function isBalanced(str){
  var stack = new Stack();
  for(var c=0;c<str.length;c++){
    var chr = str[c];
    if(isOpenBracket(chr)){
      stack.push(chr);
    }
    else if(isCloseBracket(chr)){
      var openBracket = stack.pop();
      if(!bracketsMatch(openBracket, chr))
        return false;
    }
  }
  return true;
}

- S.Abakumoff December 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int validate(char *str)
{
char stack[100];
int top = 0;
while(*str != '\0')
{
if(*str == '(' || *str == '{' || *str == '[')
{
stack[top++] = *str++; //pushing the opening braces into the stack
}
else if(*str == ')' || *str == '}' || *str == ']')
{
if(top > 0)
{
if(match(stack[--top],*str) == 1)
{
str++;
}
else
{
printf("Braces mismatch $ %c %c $ top %d\n",*str,stack[++top],top);
return 0;
}
}
else
{
printf("Lesser closing braces: %c top %d\n",*str,top);
return 0;
}
}
else
{
printf("Invalid braces\n");
return 0;
}
}
if(top == 0)
return 1;
else
{
printf("Openings braces extra (top %d)\n",top);
return 0;
}
}

- Ashish December 19, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use 3 counter variables, sb, rb and cd for square braces, round braces and curly braces respectively; increment each when its an open brace and decrement when a close brace is encountered. At the end of string all counters have to be zero and reject a string if one of the counters becomes negative!

- Anonymous January 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The thought here is to push the left bracket into stack and whenever we encounter a right bracket, pop the entry from stack and compare against the current one.

Time Complexity: O(n)
Auxiliary Space: O(n) for stack

private static int myFlag = 0;
	private static boolean checkB(String str){
		
		Stack myStack = new Stack();
		
		for (int i = 0; i < str.length(); i++) {
			
			
			if(str.charAt(i) == '(' || str.charAt(i) == '[' || str.charAt(i) == '{')
				myStack.push(str.charAt(i));
			
			if(str.charAt(i) == ')'){
				if('(' != myStack.pop().toString().charAt(0)){
					myFlag = -1;
					break;
				}
			}
			
			if(str.charAt(i) == ']'){
				if('[' != myStack.pop().toString().charAt(0)){
					myFlag = -1;
					break;
				}
			}
				
			if(str.charAt(i) == '}'){
				if('{' != myStack.pop().toString().charAt(0)){
					myFlag = -1;
					break;
				}
			}
		}
		
		if(myFlag == -1)
			return false;
		else return true;
		
	}

- UB February 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 4 vote

If there are more than 1 type of braces:
Keep putting them like numbers as
1 => (
2=> {
3=> [
and -1,-2,-3 as their respective closing braces.

Keep summing up the stack while inserting an element. Keep checking that sum does not turn negative. -ve number means that its mismatch. Also, when you receive a closeBrace, pop one element from stack and sum that with new closeBrace, sum should be 0.

- Anonymous December 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

0) Assume: we have const brace variables such as SQURE_BRACE, ROUND_BRACE, CURLY_BRACE
1) For every type of brace, have separate weightCounter
1.1) For curly braces "{}", curlyBraceWeight
1.2) For square braces "[]", squareBraceWeight
1.3) For round braces "()" - roundBracesWeight
2) Initialize all brace weights to zero
3) For every brace in the string
3.1) If it is left brace, set modVal to '+1"; if it is right, set modVal to '-1'
3.2) Check the brace type (using the const brace vars), and add modVal to that brace type's weight
3.3) If this brace type's weight hits negative value - quit the loop and report 'unbalanced'
4) After finishing the string, if any weight is not zero - report 'unbalanced'
5) Otherwise, report 'balanced'.

Assume the following Extra Library API:
- MaxBraceTypes - Returns the max no. of brace types
- GetBraceType() - Returns an integer less than MaxBraceTypes (i.e. type ids are continuous)

We could:
- Have an array of MaxBraceTypes size (inited to zero)
- Step (3.2) would be modifying the weight at that index in array of weights

Thanks,
Laxmi

- Laxmi Narsimha Rao Oruganti December 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Doesn't work for {[(}]).
Should use a stack to get the correct parenthesis, as someone have discussed below.

- havefun December 12, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

)}][{)
Will this be considered as balanced ?
or "(" followed be ")" will be considered as balanced

- jainrajrahul December 13, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

havefun - Yes, the code awfully fails on your input. Thanks for the test case. Voted down my post.

- Laxmi Narsimha Rao Oruganti December 13, 2012 | Flag


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More