Skip to content

Instantly share code, notes, and snippets.

@ben-rubin
Created December 11, 2021 19:27
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 ben-rubin/3f39fa4509db168070e7dfedb7d16503 to your computer and use it in GitHub Desktop.
Save ben-rubin/3f39fa4509db168070e7dfedb7d16503 to your computer and use it in GitHub Desktop.
/**
* Time complexity: O(6)
* Space complexity: O(3n) - almost 3x original array size? No entirely sure
*
* Assumes that the inputs are valid
*
* @param openingParenthesisIndex Zero based index of '(' in str
* @param str String to search - must be equal # of '(' and ')'
*/
const getCorrespondingClosingParenthesesIndex = (openingParenthesisIndex: number, str: string): number => {
const start: string = str.substring(0, openingParenthesisIndex + 1) // include openParenthesis index
const end: string = str.substr(openingParenthesisIndex + 1, str.length) // exclude openParenthesis index
const closingParentheses: string[] = end.split(')')
// how many '(' do we remove from the end to get our matching ')'
const openingParenthesesCount: number = start.split('(').length - 1
// remove this many parentheses from the end
const everythingUpToTarget = closingParentheses.splice(0, closingParentheses.length - openingParenthesesCount)
// put the pieces back, without the unmatched ')'
const result = (start + everythingUpToTarget.join(')'))
return result.length
}
console.log(getCorrespondingClosingParenthesesIndex(9, 'a(aa(aaaa(a(a)aa)aaa)aa)a'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment