Skip to content

Instantly share code, notes, and snippets.

@ChrisDobby
Created February 20, 2023 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisDobby/830e72b81b3434b6bd2362cfb120a7cb to your computer and use it in GitHub Desktop.
Save ChrisDobby/830e72b81b3434b6bd2362cfb120a7cb to your computer and use it in GitHub Desktop.
Given a string of parenthesis, return the number of parenthesis you need to add to the string in order for it to be balanced.
const numBalanced = (str: string) => {
const { open, closed } = str.split('').reduce(({ open, closed }, s) => ({ open: open + (s === '(' ? 1 : 0), closed: closed + (s === ')' ? 1 : 0) }), { open: 0, closed: 0 })
return Math.abs(open - closed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment