Input:
Input contains one string S which consists of big and small latin letters, digits, punctuation marks and brackets from the set []{}().
Constraint:
Constraints. The length of S is at least 1 and at most 105
Output:
If the code in S uses brackets correctly, output “Success" (without the quotes). Otherwise, output the 1-based index of the first unmatched closing bracket, and if there are no unmatched closing brackets, output the 1-based index of the first unmatched opening bracket.
Code:
console.clear();
function hashBalancedParanthesis(string) {
// Pre: The string should have ASCII characters
var len = string.length;
var stack = [];
for (var i = 0; i < len; i++) {
var char = string[i];
//console.log(stack + " : " + char);
if ('([{'.indexOf(char) !== -1) // O(3 * len)
stack.push(char);
else if (')]}'.indexOf(char) !== -1) { // O(3 * len)
// Below operations are O(n) time
var top = stack.pop();
if (top === '[' && char !== ']') return string.indexOf(char) + 1;
if (top === '{' && char !== '}') return string.indexOf(char) + 1;
if (top === '(' && char !== ')') return string.indexOf(char) + 1;
}
}
// Post: When here the stack should be empty for balanced case
if (stack.length !== 0) return string.indexOf(stack.pop()) + 1;
return true;
};
// False
console.log(hashBalancedParanthesis('('));
console.log(hashBalancedParanthesis('{[}'));
console.log(hashBalancedParanthesis('foo(bar[i);'));
// True
console.log(hashBalancedParanthesis(''));
console.log(hashBalancedParanthesis('{}[]'));
console.log(hashBalancedParanthesis('[()]'));
console.log(hashBalancedParanthesis('(())'));
console.log(hashBalancedParanthesis('foo(bar);'));
Description:
Instead of hard work since last three years I got rejected in one of the dream companies so, now I would like to have clear understanding of running time and edge cases as well as code quality.
Naming is now second priority.
As per my knowledge the above code runs in linear time \$\Theta(n)\$ where n is the string length.
PS: I am going to write a detailed analysis of my interview experience I would like to know which place would be better for it.
// Below operations are O(1) time
. Not really,indexOf
isO(n)
. \$\endgroup\$hashXyz()
? It does not output Success.) \$\endgroup\$3
. \$\endgroup\$