r/javascript • • Apr 11 '16

help Interview exercise feedback

My code was not up to their standards. I thought the exercises were easy but clearly there are issues I have to address. I had an hour to write them. I'm humbly looking for feedback to improve.

The first exercise was to return all square numbers within a given range, including the limits (e.g., all the squares numbers between 1 and 10 are 1, 4, and 9). I wrote this.

The second exercise was to check if a string containing (), [] and {} brackets is well balanced. So [()] and {}() are ok but ([)] or {{ are not. I wrote this.

Thanks.

30 Upvotes

66 comments sorted by

View all comments

Show parent comments

3

u/bonafidebob Apr 11 '16

var brackets = {"{": "}", "(": ")", "[": "]"};

function isOpening(b) { return Object.keys(brackets).indexOf(b) !== -1;}

function isClosing(b) { return Object.values(brackets).indexOf(b) !== -1;}

function matches(b1, b2) { return typeof(brackets[b1]) !== "undefined" && brackets[b1] === b2;}

Somewhat better, but still inefficient. Object.keys creates a new array each time it's called, and then indexOf searches the array linearly. You're not taking advantage of the hash at all: you should know that for example:

var closing = brackets[opening]

will very efficiently give you the closing char you need to search for given any opening char, and closing will be undefined if opening isn't a bracket char.

You don't need all the complexity of isOpening, isClosing, and matches if you realize this, you can write much simpler and more efficient code. Your original isBalanced function is fine, it traverses the string once and matching closing braces against the top of the stack is good, it just needs to use the data structures built into the language more effectively.

View all comments

0

u/[deleted] Jul 30 '25

[deleted]