Under construction

Still being built. Things may change

Shortest Regular Brackets Sequence

Interview

Time limit1sMemory limit128 MB

Summary
Given a string of brackets, find the length of the shortest regular bracket sequence that contains it as a subsequence.
Level

Medium7 of 10

Topics
Dynamic programming, Intervals, String, Implementation
Solved
No attempts yet

Problem

A regular brackets sequence is defined as follows.

  1. The empty sequence is a regular brackets sequence.
  2. If SS is a regular brackets sequence, then (S)(S) and [S][S] are also regular brackets sequences.
  3. If AA and BB are regular brackets sequences, then their concatenation ABAB is also a regular brackets sequence.

For example, all of the following are regular brackets sequences:

(), [], (()), ([]), ()[], ()[()]

None of the following are regular brackets sequences:

(, [, ), )(, ([)], ([(]

You are given a string consisting of the four characters (, ), [, and ]. Among all regular brackets sequences that contain the given string as a subsequence, find the shortest one and report its length.

Here, a string a1a2…ana_1 a_2 \dots a_n is a subsequence of a string b1b2…bmb_1 b_2 \dots b_m if there exist indices 1≤i1<i2<⋯<in≤m1 \le i_1 < i_2 < \dots < i_n \le m such that aj=bija_j = b_{i_j} for every 1≤j≤n1 \le j \le n.

Input

The first line contains a string made up only of the characters (, ), [, and ]. The string has length at most 100100 and contains no other characters. The string may be empty (an empty line), which represents the empty sequence.

Output

Print a single integer: the length of the shortest regular brackets sequence that contains the given string as a subsequence.

Examples3

  1. Example 1

    Input
    ([(]
    
    Expected output
    6
    
  2. Example 2

    Input
    ()
    
    Expected output
    2
    
  3. Example 3

    Input
    ([)]
    
    Expected output
    6