Skip to content

Instantly share code, notes, and snippets.

@avamsi
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avamsi/c663ed3dd5637dbcc844 to your computer and use it in GitHub Desktop.
Save avamsi/c663ed3dd5637dbcc844 to your computer and use it in GitHub Desktop.
from itertools import groupby
from collections import deque
for _ in xrange(int(raw_input())):
s = raw_input()
n = len(s)
k = int(raw_input())
flag = False
ret = 0
for c in s:
if c is ')':
ret -= 1
else:
ret += 1
if ret < 0:
flag = True
break
if ret != 0:
flag = True
if flag:
if k == 1:
print s
else:
print '-1'
else:
g = [i for i, _ in groupby(s)]
if k > len(g):
print '-1'
else:
if k > g.count(')'):
k -= g.count(')')
if k == g.count('('):
idx = 0
else:
d = deque(s)
while k:
while d[-1] == ')':
d.pop()
while d[-1] == '(':
d.pop()
k -= 1
idx = len(d)
else:
if k == g.count(')'):
idx = -1
else:
d = deque(s)
while k:
while d[0] == '(':
d.popleft()
while d[0] == ')':
d.popleft()
k -= 1
idx = n - len(d) - 1
l = list(s)
l[idx] = ''
print ''.join(l)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment