Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created November 22, 2023 14:49
Show Gist options
  • Select an option

  • Save optimistiks/342729fc660637101839bcea8b6dc3ed to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/342729fc660637101839bcea8b6dc3ed to your computer and use it in GitHub Desktop.
Given a string that may consist of opening and closing parentheses, your task is to check whether or not the string contains valid parenthesization.
function isValid(s) {
const stack = [];
const open = ["(", "[", "{"];
const closing = [")", "]", "}"];
for (const char of s) {
const index = closing.indexOf(char);
if (index !== -1 && stack[stack.length - 1] === open[index]) {
stack.pop();
} else {
stack.push(char);
}
}
return stack.length === 0;
}
export {
isValid
};
// tc: O(n)
// sc: O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment