Preparing for a technical interview, I solved the problem with a recursive solution.
What is the difficulty of executing a recursive function such as this? I'm more interested in an explanation, not an answer.
From my analysis - the number of operations will be half n. That is, a string of 10 characters will receive 5 function calls in the worst case. But I never saw O (n / 2) runtime. In addition, my analysis eliminates the call of an auxiliary function counterpartOf. Can someone please show me the correct analysis?
Write a function that takes a string of brackets ({}) and returns if it is balanced.
function checkBraces(input){
var c = input.length / 2;
if (input.charAt(c) !== counterpartOf(input.charAt(c-1))) {
var match = false;
return match;
} else {
if (input.length === 2){
var match = true;
return match;
} else {
input = input.substring(0,c-1) + input.substring(c+1,input.length);
return checkBraces(input);
}
}
return match;
}
function counterpartOf(brace){
closing = ['}', ')', ']'];
opening = ['{', '(', '['];
var i = opening.indexOf(brace);
var counterpart = closing[i];
return counterpart;
}