defmodule Main do def paren(str, n) do left_fn = fn -> s = str |> String.slice((n)..-1) r = ~r/^(\(*)\(\)(.*)$/ n + _paren(s, r) end right_fn = fn -> s = str |> String.slice(0..(n - 2)) r = ~r/^(.*)\(\)(\)*)$/ n - _paren(s, r) end n_char = str |> String.graphemes |> Enum.at(n - 1) case n_char do "(" -> left_fn.() ")" -> right_fn.() end end defp _paren(str, re, acc \\ 0) do case Regex.run(re, str, capture: :all_but_first) do nil -> acc + 1 [s1, s2] -> _paren(s1 <> s2, re, acc + 2) end end def main do inputs = IO.binread(:all) |> String.split k = inputs |> Enum.at(1) |> String.to_integer s = inputs |> Enum.at(2) IO.puts paren(s, k) end end