Skip to content

Instantly share code, notes, and snippets.

@joegiralt
Created October 25, 2019 05:11
Show Gist options
  • Save joegiralt/fad47aed2eb0b33d0d1cb86a147124a2 to your computer and use it in GitHub Desktop.
Save joegiralt/fad47aed2eb0b33d0d1cb86a147124a2 to your computer and use it in GitHub Desktop.
interview prep 1.
// I like parentheticals (a lot).
// "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."
// Write a function that, given a sentence like the one above, along with the position of an opening parenthesis, finds the corresponding closing parenthesis.
// Example: if the example string above is input with the number 10 (position of the first parenthesis), the output should be 79 (position of the last parenthesis).
const findParenPosition = (string, pos) => {
let openStack = [pos];
let closeStack = [];
let scanPosition = pos + 1;
while (openStack.length !== 0) {
if (string[scanPosition] === '(') {
openStack.push(scanPosition)
} else if (string[scanPosition] === ')') {
closeStack.push(scanPosition)
};
if (closeStack.length === 1 && openStack.length === 1) {
break;
} else if (closeStack.length && openStack.length) {
openStack.pop();
closeStack.pop();
};
scanPosition++;
};
return closeStack[0];
};
const string1 = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.";
findParenPosition(string1, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment