Bloomberg interview question

Find if given text does have matching [ { ( opening and closing. So ({[]}) is valid and ({)} is invalid. They should open and close in proper order.

Interview Answers

Anonymous

13 Jun 2015

private static bool OpeningClosingTags(string str) { Dictionary dict = new Dictionary(){{'{',0},{'(',0},{'[',0},{'}',0},{')',0},{']',0}}; Dictionary dict2 = new Dictionary() { { '{', '}' },{'[',']'},{'(',')'} }; foreach(var c in str) { int val=0; if (dict.TryGetValue(c, out val)) dict[c]++; } foreach(var d in dict2) { if (dict[d.Key] != dict[d.Value]) return false; } return true; }

Anonymous

13 Jun 2015

Ignore above posting, it doesn't check order of tags: private static bool OpeningClosingTagsRight(string str) { Dictionary dict = new Dictionary() { { '{', 1 }, { '(', 1 }, { '[', 1 }, { '}', '{' }, { ')', '(' }, { ']', '[' } }; // Dictionary dict2 = new Dictionary() { { '{', '}' }, { '[', ']' }, { '(', ')' } }; Stack stack = new Stack(); foreach (var c in str) { int val = 0; if (dict.TryGetValue(c, out val)) { if (val == 1) stack.Push(c); else { if (stack.Count > 0) { char opening = stack.Pop(); if (opening != dict[c]) return false; } } } } return true; }

Anonymous

17 Jul 2018

x = '{sample (text)}' openlist = [] braces_dict = {'}': '{', ')': '(', ']': '['} failed = False for i in x: if i in braces_dict.values(): openlist.append(i) elif i in braces_dict.keys(): if openlist.pop() == braces_dict[i]: continue else: failed = True break if not failed: print('code is good') else: print('code is not good')

Anonymous

17 Jul 2018

Updated: openlist = [] def is_balanced(x): braces_dict = {'}': '{', ')': '(', ']': '['} for i in x: if i in braces_dict.values(): openlist.append(i) elif i in braces_dict.keys(): if openlist and openlist.pop() == braces_dict[i]: continue else: return False if len(openlist) > 0: return False return True

Anonymous

10 Nov 2014

Using std::stack, push closing of any found opening bracket or paranthesis, when you find closing pop it out of stack if it was match, if it wasn't match, return false.

3