Interview Question


Country: United States




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

My code:

private boolean isValidParenthesis(char[] s) {
    // assume we have a map contains all type of parenthesis
    Map<Character, Character> parenthesisType = new HashMap<Character, Character>();
    parenthesisType.put('{', '}');
    parenthesisType.put('(', ')');
    parenthesisType.put('[', ']');

    // initial a stack
    Stack stack = new Stack();

    for (int i = 0; i < s.length; i++) {
        // if s[i] is a valid open parenthesis, push to stack
        if (parenthesisType.containsKey(s[i])) {
            stack.push(s[i]);
        }
        // if not, this may be a close parenthesis, so
        // check the top of stack, if it's same type
        // with s[i], remove this top open parenthesis
        else if (!stack.empty() && parenthesisType.get(stack.peek()) == s[i]) {
            stack.pop();
        }
        // if this parenthesis not exist or stack is empty, return false
        else {
            return false;
        }
    }

    // if our stack is empty, this mean s is valid parenthesis
    return stack.isEmpty();
}

- techinterviewquestion.com February 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

// ZoomBA
config = { '(' : 0 , '{' : 0 , '[' : 0 }
match = { ')' : '(' , '}' : '{' , ']' : '[' }
lfold( string.value ) -> {
  c = str($.o) 
  continue ( c @ config ){  config[c] += 1  }
  continue ( !(c @ match) ) 
  config[ match[c] ] -= 1 
  break ( config[ match[c] ] < 0 )
} 
!exists ( config ) :: { $.o.value != 0 }

- NoOne October 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
{{{ using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlgorithmsTests { [TestClass] public class AreParenthesisBalanced { private bool AreBalanced(string s) { if (string.IsNullOrEmpty(s)) { //and empty string is always balanced return true; } Stack<char> stack = new Stack<char>(); for (int i = 0; i < s.Length; i++) { switch (s[i]) { //if it is a openning, then queue it and check later case '(': stack.Push(')'); break; case '[': stack.Push(']'); break; case '{': stack.Push('}'); break; //now check the closing case ')': if (')' != stack.Pop()) return false; break; case ']': if (']' != stack.Pop()) return false; break; case '}': if ('}' != stack.Pop()) return false; break; default: throw new ApplicationException("Unexpected character."); } } // it the stack is empty, then the string is balanced return stack.Count == 0; } [TestMethod] public void BalancedTests() { Assert.IsTrue(AreBalanced(null)); Assert.IsTrue(AreBalanced(string.Empty)); Assert.IsTrue(AreBalanced("()")); Assert.IsTrue(AreBalanced("(((((()))))){{{{{()}}}}}")); Assert.IsTrue(AreBalanced("()[]")); Assert.IsTrue(AreBalanced("()[{}]")); Assert.IsFalse(AreBalanced("(")); Assert.IsFalse(AreBalanced("({)}")); Assert.IsFalse(AreBalanced("((((({{{{{")); } } } }}} - Octavio Licea February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
{{{ using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AlgorithmsTests { [TestClass] public class AreParenthesisBalanced { private bool AreBalanced(string s) { if (string.IsNullOrEmpty(s)) { //and empty string is always balanced return true; } Stack<char> stack = new Stack<char>(); for (int i = 0; i < s.Length; i++) { switch (s[i]) { //if it is a openning, then queue it and check later case '(': stack.Push(')'); break; case '[': stack.Push(']'); break; case '{': stack.Push('}'); break; //now check the closing case ')': if (')' != stack.Pop()) return false; break; case ']': if (']' != stack.Pop()) return false; break; case '}': if ('}' != stack.Pop()) return false; break; default: throw new ApplicationException("Unexpected character."); } } // it the stack is empty, then the string is balanced return stack.Count == 0; } [TestMethod] public void BalancedTests() { Assert.IsTrue(AreBalanced(null)); Assert.IsTrue(AreBalanced(string.Empty)); Assert.IsTrue(AreBalanced("()")); Assert.IsTrue(AreBalanced("(((((()))))){{{{{()}}}}}")); Assert.IsTrue(AreBalanced("()[]")); Assert.IsTrue(AreBalanced("()[{}]")); Assert.IsFalse(AreBalanced("(")); Assert.IsFalse(AreBalanced("({)}")); Assert.IsFalse(AreBalanced("((((({{{{{")); } } } }}} - Octavio Licea February 28, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

What are you trying to say ? :P

- Anonymous February 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var pattern = "(){}[]";

var balance = function(s) {
var compareList = [];

for(var i=0; i<s.length; i++) {
// if open char
if(pattern.indexOf(i) % 2 === 0) {
compareList.push(s[i]);
} else {
// if open one exists, remove it
if(compareList.indexOf(s[i-1]) >= 0) {
compareList.splice(compareList.indexOf(s[i-1]),1);
// blow up otherwise
} else {
return false;
}
}
}
return compareList.length === 0;
};

- javascript answer February 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var pattern = "(){}[]";

var balance = function(s) {
	var compareList = [];
  
  for(var i=0; i<s.length; i++) {
  	// if open char
  	if(pattern.indexOf(i) % 2 === 0) {
    	compareList.push(s[i]);
    } else {
    	// if open one exists, remove it
    	if(compareList.indexOf(s[i-1]) >= 0)  {
      	compareList.splice(compareList.indexOf(s[i-1]),1);
      // blow up otherwise
      } else {
      	return false;
      }
    }
  }
  return compareList.length === 0;
};

- Anonymous February 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

c#.
Time O(n).
Space O(1).
A little bit more tricky than solution with stack but it saves running space.

public static bool ValidateBrackets2( string str ) {
    const uint n = 0;
    // all possible pairs of brackets in forward order
    var dic1 = new Dictionary<char, char> { {'{', '}'}, {'(', ')'}, {'[', ']'}, {'<', '>'} };
    // all possible pairs of brackets in reverse order
    var dic2 = new Dictionary<char, char> { {'}', '{'}, {')', '('}, {']', '['}, {'>', '<'} };
    // all possible pairs of brackets coupled
    var dic3 = new Dictionary<string, uint> { {"{}", n}, {"()", n}, {"[]", n}, {"<>", n} };
    // all possible closing brackets
    var dic0 = new Dictionary<char, uint> { { '}', n }, { ')', n }, { ']', n }, { '>', n } };

    foreach ( char ch in str ) {
        if ( dic1.ContainsKey( ch ) ) {
            dic3[ ch.ToString() + dic1[ ch ] ]++;
            dic0[ dic1[ ch ]  ] = dic0.Values.Max() + 1;
            continue;
        }
        if ( dic2.ContainsKey( ch ) ) {
            if ( dic0[ ch ] != dic0.Values.Max() ) { return false; }
            try {
                checked { dic3[ dic2[ ch ] + ch.ToString() ]--; }
                dic0[ ch ] = (dic3[ dic2[ ch ] + ch.ToString() ] == 0) 
                        ? 0 
                        : dic0.Values.Where( x => x > 0 ).Min() - 1;
            } catch ( OverflowException ) {
                return false;
            }
        }
    }
    return dic3.All( item => item.Value == 0 );
}

- zr.roman February 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/**
 * Javascript Implementation.
 * parenthesis-checker

 Given an expression string exp, examine whether the pairs and the orders
 of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
 For example, the program should print
 'balanced' for exp = “[()]{}{[()()]()}” and
 'not balanced' for exp = “[(])”

 Input:
 The first line of input contains an integer T denoting the number of test cases.
 Each test case consists of a string of expression, in a separate line.

 Output:
 Print 'balanced' without quotes if the pair of parenthesis are balanced else print
 'not balanced' in a separate line.
 */


function parenthesisChecker(str) {
  let stack = [];
  const openingParenthesis = ['{','(','['];
  const closingParenthesis = ['}',')',']'];
  let result = true;

  for(let index = 0, length = str.length; index < length; index++) {
    const char = str[index];
    if(openingParenthesis.indexOf(char) > -1){
      stack.push(char);
    }
    if(closingParenthesis.indexOf(char) > -1){
      switch(stack.pop()){
        case '{':
          result = char === '}';
          break;
        case '(':
          result = char === ')';
          break;
        case '[':
          result = char === ']';
          break;
      }
      // if result is false then immidiately return 'Non balanced'
      if(!result) {
        return "String is not balanced";
      }
    }
    //console.log("Stack is = " + stack);
  }
  return 'String is balanced';
}

const str = '[()]{}{[()()]()}';
console.log("parenthesis-checker -> " +  parenthesisChecker(str));

- Amit Bansal March 06, 2018 | Flag Reply


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