Advertisement
Iam_Sandeep

1963. Minimum Number of Swaps to Make the String Balanced

Jun 19th, 2022 (edited)
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. #using stack
  2. class Solution:
  3.     def minSwaps(self, s: str) -> int:
  4.         st=[]
  5.         for i in s:
  6.             if i=='[':#only store op bracks
  7.                 st.append(i)
  8.             else:
  9.                 if st:st.pop()
  10.         n=len(st)
  11.         return n//2+n%2#e.g. ]][[,][
  12. #without stack
  13. class Solution:
  14.     def minSwaps(self, s: str) -> int:
  15.         ans=0
  16.         c=0
  17.         for i in s:
  18.             c=c+1 if i=='[' else c-1
  19.             if c<0:
  20.                 ans+=1
  21.                 c=1
  22.         return ans
  23. '''
  24. Here we are maintaining the value c which pairs out brackets.
  25. But whenever we see unpaired ] i.e. c<0 at any instance then we might have to take a '[' and swap with . Lets say there is a '[' some where and you swapped here(assume). Now c has to become 1 to match some upcoming ].
  26. return the swaps
  27. '''
  28. #Method2:
  29.    '''
  30.   The idea is to traverse our string and check the biggest possible disbalance. For example if we look at ]]][]]][[[[[, for traversals we have:
  31. -1, -2, -3, -2, -3, -4, -5, -4, -3, -2, -1, 0 and the biggest disbalance is equal to 5. What we can do in one swap of brackets is to decreas it at most by 2: for this we need to take the leftest ] with negative balance and the rightest [ with negative balance and change them. For example in our case we have:
  32.  
  33. []][]]][[[[] : [1, 0, -1, 0, -1, -2, -3, -2, -1, 0, 1, 0]
  34.  
  35. [][[]]][][[] : [1, 0, 1, 2, 1, 0, -1, 0, -1, 0, 1, 0]
  36.  
  37. [][[]][[]][] : [1, 0, 1, 2, 1, 0, 1, 2, 1, 0, 1, 0]
  38.  
  39. Complexity
  40.  
  41. Time complexity is O(n) to traverse our string, space is O(1).
  42.   '''
  43. class Solution:
  44.     def minSwaps(self, s):
  45.         bal, ans = 0, 0
  46.         for symb in s:
  47.             if symb == "[": bal += 1
  48.             else: bal -= 1
  49.             ans = min(bal, ans)
  50.         return (-ans + 1)//2
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement