Created
December 11, 2021 19:27
-
-
Save ben-rubin/3f39fa4509db168070e7dfedb7d16503 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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