William Parsons
BANNED
- Mar 16, 2020
- 60
- 24
I was recently denied for a full-stack developer job with no explanation (maybe they just wanted free code) at a well-known proxy provider company after solving this coding challenge.
I'm always looking to improve my skills, so I'd like to know if the BHW scripting pros have a better way to solve this:
Problem
Implement a JavaScript function verify(string) which verifies whether brackets within a string are correctly nested. You need to consider only three kinds: (), [] and <> brackets.
My Solution
[formatted for readability]
I decided the best possible way was to use JSON.parse() since it already has nested validation.
I sanitized the input string and converted each parenthesis value to valid JSON format.
Performance can be further improved by creating a polyfill for JSON.parse().
Edit: "[" was previously translated to "[[" because "{" was previously translated to "[".
This solution also allows defining custom brackets, such as "start" and "stop" (and not requiring to explode the string):
I'm always looking to improve my skills, so I'd like to know if the BHW scripting pros have a better way to solve this:
Problem
Implement a JavaScript function verify(string) which verifies whether brackets within a string are correctly nested. You need to consider only three kinds: (), [] and <> brackets.
Code:
verify("---(++++)----"); // -> 1
verify(""); // -> 1
verify("before ( middle []) after "); // -> 1
verify(") ("); // -> 0
verify("<( >)"); // -> 0
verify("( [ <> () ] <> )"); // -> 1
verify(" ( [)"); // -> 0
My Solution
[formatted for readability]
Code:
var verify = function(string) {
const parentheses = {
'[': '[',
']': ']',
'(': '[[',
')': ']]',
'<': '[[[',
'>': ']]]'
};
let sanitizedString = '';
for (i = 0; i < string.length; i++) {
let closingStringIndex = 0;
let openingStringIndex = 0;
if (
(openingStringIndex = ('([<').indexOf(string[i]) + 1) > 0 ||
(closingStringIndex = ('>])').indexOf(string[i]) + 1) > 0
) {
sanitizedString += (sanitizedString && openingStringIndex ? ',' : '') + (openingStringIndex ? '"' + i + '": ' + parentheses[string[i]] + '{"' + i + '": "_"' : '}' + parentheses[string[i]]);
}
}
try {
return +(typeof JSON.parse('[{' + sanitizedString + '}]') === 'object');
} catch {
return 0;
}
};
I decided the best possible way was to use JSON.parse() since it already has nested validation.
I sanitized the input string and converted each parenthesis value to valid JSON format.
Performance can be further improved by creating a polyfill for JSON.parse().
Edit: "[" was previously translated to "[[" because "{" was previously translated to "[".
This solution also allows defining custom brackets, such as "start" and "stop" (and not requiring to explode the string):
Code:
const parentheses = {
'"start"': '[[[[',
'"stop"': ']]]]'
};
Last edited: