Under construction

Still being built. Things may change

Bracket Match

Time limit2sMemory limit512 MB

Summary
Given a lowercase string S, find the lexicographically smallest matching bracket sequence, or print -1 if none exists.
Level

Medium7 of 10

Topics
Stack, Greedy, String
Solved
No attempts yet

Problem

A valid bracket sequence is defined as follows.

  • The empty string is a valid bracket sequence.
  • If BB is a valid bracket sequence, then (B)(B) is a valid bracket sequence.
  • If LL and RR are both valid bracket sequences, then their concatenation LRLR is a valid bracket sequence.

Let BB be a valid bracket sequence of length NN, and let BiB_i be its ii-th character. Two indices ii and jj with 1≤i<j≤N1 \le i < j \le N are matching brackets when both of these hold.

  • BiB_i is ( and BjB_j is ).
  • j=i+1j = i + 1, or the substring Bi+1Bi+2…Bj−1B_{i+1} B_{i+2} \dots B_{j-1} is a valid bracket sequence.

Let SS be a string of lowercase letters, and let SiS_i be its ii-th character. A valid bracket sequence BB matches SS when both of these hold.

  • BB has the same length as SS.
  • For every pair of indices i<ji < j, if BiB_i and BjB_j are matching brackets, then Si=SjS_i = S_j.

You are given a string SS of NN lowercase letters. Find the lexicographically smallest valid bracket sequence that matches SS.

Input

The first line contains a string SS of NN lowercase letters.

  • 2≤N≤1000002 \le N \le 100000
  • A bracket sequence AA is lexicographically smaller than a bracket sequence BB if there is an index ii (1≤i≤N1 \le i \le N) such that Aj=BjA_j = B_j for every j<ij < i and Ai<BiA_i < B_i.
  • The character ( is lexicographically smaller than the character ).

Output

Print the lexicographically smallest valid bracket sequence that matches SS. If no such sequence exists, print -1.

Examples8

  1. Example 1

    Input
    abbaaa
    
    Expected output
    (()())
    
  2. Example 2

    Input
    abab
    
    Expected output
    -1
    
  3. Example 3

    Input
    aa
    
    Expected output
    ()
    
  4. Example 4

    Input
    ab
    
    Expected output
    -1
    
  5. Example 5

    Input
    aaaa
    
    Expected output
    (())
    
  6. Example 6

    Input
    aabb
    
    Expected output
    ()()
    
  7. Example 7

    Input
    aabbaa
    
    Expected output
    ((()))
    
  8. Example 8

    Input
    aabbaabb
    
    Expected output
    ((()))()