1673. Bracket Partners
A code formatter has to know which parentheses belong together. The string s is a balanced sequence made only of '(' and ')'. Return an integer array partner of the same length as s in which partner[i] is the index of the bracket that is matched with the bracket at position i. An opening bracket and its closing bracket are partners of each other, and each ')' is matched with the nearest still-unmatched '(' on its left.
Scan s once while keeping a stack of the indices of open brackets that have not been closed yet; every ')' pops the top index and records the pair in both directions. The scan takes O(n) time and O(n) space for n = s.length, with 2 <= n <= 1000 and s guaranteed to be balanced.
Example 1
- Input:
- s = "()"
- Output:
- [1,0]
- Explanation:
The two brackets are partners of each other.
Example 2
- Input:
- s = "(())"
- Output:
- [3,2,1,0]
- Explanation:
The outer pair is (0, 3) and the inner pair is (1, 2).
Example 3
- Input:
- s = "()(())"
- Output:
- [1,0,5,4,3,2]
- Explanation:
The first pair is (0, 1), then (2, 5) wraps (3, 4).
Constraints
2 ≤ s.length ≤ 1000; s is a balanced bracket sequence of '(' and ')'
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)