Brackets
InterviewTime limit2sMemory limit512 MB
Given a bracket string, decide whether flipping the brackets in at most one contiguous segment can turn the whole string into a balanced, valid bracket sequence.
- Level
Medium6 of 10
- Topics
- Greedy, Prefix sum, String, Implementation
- Solved
- No attempts yet
Problem
A bracket sequence made of ( and ) is valid exactly when the following rules build it.
- The empty sequence is valid.
- If is a valid bracket sequence, then is a valid bracket sequence.
- If and are valid bracket sequences, then their concatenation is a valid bracket sequence.
For example, (()), ()(), and (()())() are valid bracket sequences, while ( and ()) are not.
You are given a bracket sequence of length . It might not be valid. Decide whether at most one segment inversion makes it a valid bracket sequence. A segment inversion picks two 1-based indices and () and inverts every bracket at an index in the closed interval . After the inversion, a left bracket ( becomes a right bracket ), and a right bracket ) becomes a left bracket (.
Inverting the segment makes ())( valid. Inverting the segment makes ())) valid, and inverting the segment does the same. No segment inversion makes )))( valid.
Input
One line holds the bracket sequence. Its length is between 1 and 5000, and it contains only ( and ).
Output
Print possible if at most one segment inversion makes the bracket sequence valid, and impossible otherwise.