Balance the Brackets Your objective: Given a string of brackets, output the minimum Damerau-Levenshtein Distance required to turn the input string into a string where the brackets are balanced.
Input
The input string will only contain brackets and no other characters. That is, it is a combination of any of the characters in (){}[]&lt;&gt;. You may take input as either a string or an array of characters. You may not make any other assumptions about the input string; it may be arbitrarily long (up to the maximum size supported by your language), it may be empty, the brackets may already be balanced, etc.
Damerau-Levenshtein Distance
The Damerau-Levenshtein Distance between two strings is the minimum number of insertions, deletions, single-character substitutions, and transpositions (swapping) of two adjacent characters.
Output
The output should be the minimum Damerau-Levenshtein Distance between the input string and a string in which the brackets are matched. Output should be a number, not the resulting balanced string.
A pair of brackets is considered &quot;matched&quot; if the opening and closing brackets are in the right order and have no characters inside of them, such as
()
[]{}

Or if every sub-element inside of it is also matched.
[()()()()]
{&lt;[]&gt;}
(()())

Sub-elements can also be nested several layers deep.
[(){&lt;&gt;&lt;&gt;[()]}&lt;&gt;()]
&lt;[{((()))}]&gt;

(Thanks to @DJMcMayhem for the definition)
Test Cases
Input                   Possible Balanced       Output

Empty                   Empty                   0
[](){}&lt;&gt;                [](){}&lt;&gt;                0           
[(){}&lt;&gt;                 [(){}&lt;&gt;]                1           
[(])                    []()                    1           
[[[[[[[[                [][][][]                4
(](&lt;&gt;}[&gt;(}&gt;&gt;&lt;(&gt;(({}]    ()(&lt;&gt;)[(&lt;&gt;&lt;&gt;){}]        7
&gt;]{])&lt;                  []{()}                  3
([)}}&gt;[                 (){}&lt;&gt;                  4
{&lt;((&lt;&lt;][{{}&gt;[&lt;)         &lt;&gt;(&lt;&lt;[]&gt;{}&gt;[])          5
{&gt;&lt;({((})&gt;}}}{(}}       {&lt;&gt;&lt;({()})&gt;}{}{()}      4
(](&lt;)&gt;}[&gt;(}&gt;&gt;{]&lt;&lt;(]]    (&lt;()&lt;&gt;&lt;&lt;&gt;()&gt;&gt;[])&lt;()&gt;    9
}})(                    {}()                    2

(Thanks to @WheatWizard for solving half of the test cases)
This is code-golf, fewest bytes wins!
Your submissions should be testable, meaning it should output a result for  each test case in no more than an hour.
Brain-Flak, 1350 bytes

{({}(())(&lt;&gt;))&lt;&gt;({(()()()())&lt;{({}[()])&lt;&gt;}{}&gt;}{}&lt;&gt;({&lt;({}[()])&gt;{()(&lt;{}&gt;)}}{}{}&lt;&gt;))&lt;&gt;}&lt;&gt;([[]]){([[]({}()&lt;&gt;)]&lt;&gt;)&lt;&gt;{(({}())&lt;&lt;&gt;(({})&lt;(({}(&lt;()&gt;))&lt;&gt;({}))([(())()()]){&lt;&gt;({}())}{}{&lt;&gt;{}&lt;&gt;({}()){(((({}&lt;(({}&lt;&gt;)&lt;{({}()&lt;([(){}])&gt;)}{}&gt;)&lt;&gt;(({}(&lt;&gt;))&lt;{({}()&lt;([(){}])&gt;)}{}&lt;&gt;&gt;)&gt;&lt;&gt;({}))(&lt;(((({}({})[()])[()()]&lt;&gt;({}))&lt;&gt;[({})({}){}]({}&lt;&gt;))&lt;&gt;[(({}&lt;&gt;)&lt;&gt;({}&lt;&gt;)&lt;&gt;)])&lt;&gt;&gt;)))[()](&lt;()&gt;)&lt;&lt;&gt;(({})&lt;({}{}()){({}()&lt;({}&lt;&gt;)&lt;&gt;&gt;)}{}&lt;&gt;(({})&lt;&lt;&gt;(({}&lt;&gt;))&gt;)&lt;&gt;(())&gt;){({}[()()]&lt;(&lt;([({[{}]&lt;(({})()&lt;&gt;[({})]&lt;&gt;)&gt;{()(&lt;{}&gt;)}}{}&lt;(({})&lt;&gt;[()({}&lt;(({}&lt;&lt;&gt;({}&lt;&gt;)&lt;&gt;(({})&lt;&gt;)&gt;)&lt;&gt;[(){}])&lt;&gt;&gt;)]&lt;&gt;)&gt;{()(&lt;{}&gt;)}{}(){[()](&lt;{}&gt;)}&lt;&lt;&gt;{({}&lt;&gt;)&lt;&gt;}{}&gt;)]({}{}))&gt;)&lt;&gt;{({}&lt;&gt;)&lt;&gt;}&gt;)}{}{}&lt;&gt;{}{}{({}&lt;&gt;)&lt;&gt;}{}{}(&lt;&gt;)&lt;&gt;{({}&lt;&gt;)&lt;&gt;}{}{(&lt;{}&gt;)&lt;&gt;{({}&lt;&gt;)&lt;&gt;}&lt;&gt;({}&lt;{}&gt;){({}&lt;&gt;)&lt;&gt;}}{}((({}&lt;({}({})({})&lt;{{}&lt;&gt;{}(&lt;&gt;)}{}(((({}&lt;({}&lt;&gt;)&gt;)&lt;&gt;)))&lt;&gt;&gt;)&lt;&gt;&gt;)&lt;&gt;&lt;({}&lt;({}&lt;&lt;&gt;(()())&gt;)&gt;)&gt;)&lt;&lt;&gt;({}&lt;{}{({}&lt;&gt;)([()()()]){((({}()()&lt;&gt;))[()]&lt;(({()(&lt;{}&gt;)}{})&lt;&gt;({}&lt;(({}&lt;&lt;&gt;({}[()()](()[({})({})]({[()](&lt;{}&gt;)}{}&lt;&gt;{}&lt;(({})&lt;&gt;)&gt;)&lt;&gt;))&gt;)&lt;&gt;)&gt;)&lt;&gt;)&lt;&gt;({}&lt;({}&lt;({}&lt;({}&lt;&gt;)&gt;)&gt;)&gt;)&gt;)}{}{}&lt;&gt;}&lt;&gt;{}{}{}{}{}{}{}{}&gt;)&gt;)&gt;)}{}({}&lt;({}&lt;{({}&lt;(({}){({}())}{}{}&lt;(({}){({}())}{}{}&lt;&gt;)&gt;)&gt;)&lt;&gt;}&lt;&gt;{((({}(()()){([{}](&lt;({}(&lt;()&gt;)&lt;&gt;){({}&lt;({}&lt;&gt;)&gt;(())&lt;&gt;)}{}&gt;({})&lt;&lt;&gt;{{}({}&lt;&gt;)&lt;&gt;}{}&gt;))([{}()]{})}{})))&lt;&gt;(({}))&lt;&gt;{&lt;&gt;({}[()])}{}({}&lt;&lt;&gt;{}{}{&lt;&gt;}&gt;)&lt;&gt;{}}&lt;&gt;(({}&lt;&gt;){[()](&lt;{}&gt;)}{})(&lt;&gt;)&gt;)&gt;)&lt;&gt;(&lt;({}&lt;&gt;)&gt;)&lt;&gt;}&lt;&gt;{}({}&lt;(({}){({}())}{}{}){({}&lt;({}&lt;&gt;)&gt;(())&lt;&gt;)}{}{}&gt;)&lt;&gt;{{}({}&lt;&gt;)&lt;&gt;}{}&gt;)&lt;&gt;&gt;)}{}&lt;&gt;([[]{}])}{}(([]){&lt;{}{}&gt;([])}{}&lt;&gt;){({}[()]&lt;{}&gt;)}{}({}&lt;&gt;)


Try it online!

With constant-speed comparisons and pointer dereferencing, this algorithm is O(n3).  Unfortunately, Brain-Flak has neither of these, so this program runs in O(n5) time instead.  The longest test case takes about 15 minutes.

Simplifying results

To see that my algorithm works, we need to show some results that reduce the search space considerably.  These results rely on the fact that the target is an entire language instead of just one specific string.


No insertions are needed.  Instead, you can just remove the bracket that the inserted character would eventually match.
You will never need to remove a bracket, then swap its two neighbors.  To see this, assume wlog that the removed bracket is (, so we are transforming a(c to ca in two steps.  By changing c and inserting a copy, we can reach ca() in two steps without a swap.  (This insertion can then be removed by the above rule.)
The same bracket will never need to be swapped twice.  This is a standard fact about the Damerau-Levenshtein distance in general.


Another simplifying result that I didn't use, because accounting for them would cost bytes:


If two brackets are swapped, and they don't match each other, the eventual match to each of those brackets will never be changed or swapped.


The algorithm

When any string is reduced to a balanced string, one of the following will be true:


The first bracket is deleted.
The first bracket stays where it is and matches the bracket at some position k (possibly after changing one or both of them).
The first bracket is swapped with the second, which in turn matches the bracket at position k.


In the second case, the bracket at position k may have swapped with one of its neighbors.  In either of the latter two cases, the string between the (possibly newly) first bracket and the bracket that started in position k must be edited to a balanced string, as does the string consisting of everything after k.

This means that a dynamic programming approach may be used.  Since a swapped bracket need not be swapped again, we only need to consider contiguous substrings, as well as subsequences formed by removing the second character and/or the penultimate character from such a substring.  Hence, there are only O(n2) subsequences we need to look at.  Each of those has O(n) possible ways to match (or delete) the first bracket, so the algorithm would be O(n3) under the conditions above.

The data structure

The right stack includes the brackets from the original string, with two bytes per bracket.  The first entry determines the entire bracket, and is chosen such that matched brackets have a difference of exactly 1.  The second entry only determines whether it is an opening bracket or a closing bracket: this determines how many changes it takes for two brackets to match each other.  No implicit zeros below this are ever made explicit, so that we can use [] to get the total length of this string.

Each substring under consideration is represented by two numbers in the range 0 to 2n: one for the beginning position, and one for the end.  The interpretation is as follows:


A substring starting at 2k will start at position k (0-indexed), and the second character is not removed.
A substring starting at 2k+1 will start at position k, and the second character is removed due to having been swapped left.
A substring ending at 2k will end just before position k (i.e., the range is left-inclusive and right-exclusive.)
A substring ending at 2k-1 will end just before position k, and the penultimate character is removed due to having been swapped right.


Some ranges (k to k+1, 2k+1 to 2k+1, 2k+1 to 2k+3, and 2k+1 to 2k+5) make no physical sense.  Some of those show up as intermediate values anyway, because it's easier than adding additional checks to avoid them.

The left stack stores the number of edits needed to convert each substring into a balanced string.  The edit distance for the interval (x,y) is stored at depth x + y(y-1)/2.

During the inner loop, entries are added above the left stack to denote which moves are possible.  These entries are 5 bytes long.  Counting from the top, the numbers are d+1, y1, x1, y2, x2, where the move costs d edit steps and divides the substring into (x1,y1) and (x2,y2).

The code

Description to come.  For now, here's my working copy of the code.  Some comments may be inconsistent with terminology.

# Determine bracket type for each byte of input
{({}(())(&lt;&gt;))&lt;&gt;({(()()()())&lt;{({}[()])&lt;&gt;}{}&gt;}{}&lt;&gt;({&lt;({}[()])&gt;{()(&lt;{}&gt;)}}{}{}&lt;&gt;))&lt;&gt;}

# For every possible interval length:
&lt;&gt;([[]]){

  # Compute actual length
  ([[]({}()&lt;&gt;)]&lt;&gt;)

  # Note: switching stacks in this loop costs only 2 bytes.
  # For each starting position:
  # Update/save position and length
  &lt;&gt;{(({}())&lt;&lt;&gt;(({})&lt;

    # Get endpoints
    (({}(&lt;()&gt;))&lt;&gt;({}))

    # If length more than 3:
    ([(())()()]){&lt;&gt;({}())}{}{

      # Clean up length-3 left over from comparison
      &lt;&gt;{}&lt;&gt;

      # Initialize counter at 2
      # This counter will be 1 in the loop if we're using a swap at the beginning, 0 otherwise
      ({}())

      # For each counter value:
      {

        # Decrement counter and put on third stack
        (((({}&lt;

          # Do mod 2 for end position
          (({}&lt;&gt;)&lt;{({}()&lt;([(){}])&gt;)}{}&gt;)&lt;&gt;

          # Do mod 2 for start position
          (({}(&lt;&gt;))&lt;{({}()&lt;([(){}])&gt;)}{}&lt;&gt;&gt;)

        # Subtract 1 from counter if swap already happened
        &gt;&lt;&gt;({}))(&lt;

          # Compute start position of substrings to consider
          (((({}({})[()])[()()]&lt;&gt;({}))

            # Compute start position of matches to consider
            &lt;&gt;[({})({}){}]({}&lt;&gt;))&lt;&gt;

            # Compute end position of matches to consider
            [(({}&lt;&gt;)&lt;&gt;({}&lt;&gt;)&lt;&gt;)]

          # Push total distance of matches
          )

        # Push counter as base cost of moves
        # Also push additional copy to deal with length 5 intervals starting with an even number
        &lt;&gt;&gt;)))[()](&lt;()&gt;)&lt;

          # With match distance on stack
          &lt;&gt;(({})&lt;

            # Move to location in input data
            ({}{}()){({}()&lt;({}&lt;&gt;)&lt;&gt;&gt;)}{}

            # Make copy of opening bracket to match
            &lt;&gt;(({})&lt;&lt;&gt;(({}&lt;&gt;))&gt;)

          # Mark as first comparison (swap allowed)
          &lt;&gt;(())&gt;)

          # For each bracket to match with:
          {({}[()()]&lt;

            (&lt;([(

              # If swap is allowed in this position:
              {

                # Subtract 1 from cost
                [{}]

                # Add 1 back if swap doesn't perfectly match
                &lt;(({})()&lt;&gt;[({})]&lt;&gt;)&gt;{()(&lt;{}&gt;)}

              }{}

              # Shift copy of first bracket over, while computing differences
              &lt;(({})&lt;&gt;[()({}&lt;(({}&lt;&lt;&gt;({}&lt;&gt;)&lt;&gt;(({})&lt;&gt;)&gt;)&lt;&gt;[(){}])&lt;&gt;&gt;)]&lt;&gt;)&gt;

              # Add 1 if not perfectly matched
              {()(&lt;{}&gt;)}{}

              # Add 1 if neither bracket faces the other
              # Keep 0 on stack to return here
              (){[()](&lt;{}&gt;)}

              # Return to start of brackets
              &lt;&lt;&gt;{({}&lt;&gt;)&lt;&gt;}{}&gt;

            # Add to base cost and place under base cost
            )]({}{}))&gt;)

            # Return to spot in brackets
            # Zero here means swap not allowed for next bracket
            &lt;&gt;{({}&lt;&gt;)&lt;&gt;}

          &gt;)}

          # Cleanup and move everything to right stack
          {}{}&lt;&gt;{}{}{({}&lt;&gt;)&lt;&gt;}{}

          # Remove one copy of base cost, and move list of costs to right stack
          {}(&lt;&gt;)&lt;&gt;{({}&lt;&gt;)&lt;&gt;}{}

          # If swap at end of substring, remove second-last match
          {(&lt;{}&gt;)&lt;&gt;{({}&lt;&gt;)&lt;&gt;}&lt;&gt;({}&lt;{}&gt;){({}&lt;&gt;)&lt;&gt;}}{}

          # Put end of substring on third stack
          ((({}&lt;({}({})({})&lt;

            # If swap at beginning of substring, remove first match
            {{}&lt;&gt;{}(&lt;&gt;)}{}

            # Move start of substring to other stack for safekeeping
            (((({}&lt;({}&lt;&gt;)&gt;)&lt;&gt;)))

          # Create "deletion" record, excluding cost
          &lt;&gt;&gt;)&lt;&gt;&gt;)&lt;&gt;

          # Move data to left stack
          &lt;({}&lt;({}&lt;&lt;&gt;

            # Add cost to deletion record
            (()())

          &gt;)&gt;)&gt;)

          # Put start position on third stack under end position
          &lt;&lt;&gt;({}&lt;

            # For each matching bracket cost:
            {}{

              # Move cost to left stack
              ({}&lt;&gt;)

              # Make three configurations
              ([()()()]){

                # Increment counter
                ((({}()()&lt;&gt;))[()]&lt;

                  # Increment cost in first and third configurations
                  (({()(&lt;{}&gt;)}{})&lt;&gt;({}&lt;

                    # Keep last position constant
                    (({}&lt;

                      # Beginning of second interval: 1, 2, 1 past end of first
                      &lt;&gt;({}[()()]

                        # End of first interval: -3, -1, 1 plus current position
                        (()[({})({})]

                          # Move current position in first and third configurations
                          ({[()](&lt;{}&gt;)}{}&lt;&gt;{}&lt;

                            (({})&lt;&gt;)

                          &gt;)

                        &lt;&gt;)

                      )

                    &gt;)&lt;&gt;)

                  &gt;)&lt;&gt;)

                  # Move data back to left stack
                  &lt;&gt;({}&lt;({}&lt;({}&lt;({}&lt;&gt;)&gt;)&gt;)&gt;)

                &gt;)

              }{}

            {}&lt;&gt;}

            # Eliminate last entry
            # NOTE: This could remove the deletion record if no possible matches.  This is no loss (probably).
            &lt;&gt;{}{}{}{}{}{}{}{}

        # Restore loop variables
        &gt;)&gt;)&gt;)

      }{}

      # With current endpoints on third stack:
      ({}&lt;({}&lt;

        # For all entries
        {

          # Compute locations and move to right stack
          ({}&lt;(({}){({}())}{}{}&lt;(({}){({}())}{}{}&lt;&gt;)&gt;)&gt;)&lt;&gt;

        }

        # For all entries (now on right stack):
        &lt;&gt;{

          # Cost of match
          ((({}

            # Do twice:
            (()()){([{}](

              # Add cost of resulting substrings
              &lt;({}(&lt;()&gt;)&lt;&gt;){({}&lt;({}&lt;&gt;)&gt;(())&lt;&gt;)}{}&gt;({})&lt;&lt;&gt;{{}({}&lt;&gt;)&lt;&gt;}{}&gt;

            # Evaluate as sum of two runs
            ))([{}()]{})}{}

          )))

          # Find smaller of cost and current minimum
          &lt;&gt;(({}))&lt;&gt;{&lt;&gt;({}[()])}{}

          # Push new minimum in place of old minimum
          ({}&lt;&lt;&gt;{}{}{&lt;&gt;}&gt;)

          &lt;&gt;{}

        }

        # Subtract 1 if nonzero
        &lt;&gt;(({}&lt;&gt;){[()](&lt;{}&gt;)}{})(&lt;&gt;)

      &gt;)&gt;)

      &lt;&gt;(&lt;({}&lt;&gt;)&gt;)&lt;&gt;

    # Otherwise (length 3 or less), use 1 from earlier as cost.
    # Note that length 0-1 is impossible here.
    }&lt;&gt;{}

    # With cost on third stack:
    ({}&lt;

      # Find slot number to store cost of interval
      (({}){({}())}{}{})

      # Move to slot
      {({}&lt;({}&lt;&gt;)&gt;(())&lt;&gt;)}{}

    # Store new cost
    {}&gt;)

    # Move other slots back where they should be
    &lt;&gt;{{}({}&lt;&gt;)&lt;&gt;}{}

  Restore length/position for next iteration
  &gt;)&lt;&gt;&gt;)}

  # Clear length/position from inner loop
  {}&lt;&gt;([[]{}])

}{}

(([]){&lt;{}{}&gt;([])}{}&lt;&gt;){({}[()]&lt;{}&gt;)}{}({}&lt;&gt;)