Iam_Sandeep

838. Push Dominoes

Jul 21st, 2022 (edited)
527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.30 KB | None | 0 0
  1. '''
  2. There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
  3.  
  4. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
  5.  
  6. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
  7.  
  8. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
  9.  
  10. You are given a string dominoes representing the initial state where:
  11.  
  12. dominoes[i] = 'L', if the ith domino has been pushed to the left,
  13. dominoes[i] = 'R', if the ith domino has been pushed to the right, and
  14. dominoes[i] = '.', if the ith domino has not been pushed.
  15. Return a string representing the final state.
  16. '''
  17. #Method 1
  18. class Solution:
  19.     def pushDominoes(self, d: str) -> str:
  20.         d='L'+d+'R'#We added these two L and R so that we can create partitions perfectly.
  21.         ans=[]
  22.         l=0
  23.         for r in range(1,len(d)):
  24.             if d[r]=='.':
  25.                 continue
  26.             mid=r-l-1#how many '.' are in between l and r
  27.             if d[l]==d[r]:
  28.                 ans.append(d[l]*(mid)+d[r])
  29.             elif d[l]=='L' and d[r]=='R':
  30.                 ans.append('.'*mid+d[r])
  31.             elif d[l]=='R' and d[r]=='L':
  32.                 ans.append('R'*(mid//2)+'.'*(mid%2)+'L'*(mid//2)+d[r])
  33.             l=r
  34.         return ''.join(ans)[:-1]#ignore right most domino
  35. #Method 2
  36. class Solution:
  37.     def pushDominoes(self, d: str) -> str:
  38.         q=deque()
  39.         n=len(d)
  40.         d=list(d)
  41.         for i,j in enumerate(d):
  42.             if j!='.':
  43.                 q.append((i,j))
  44.         while q:
  45.             i,val=q.popleft()
  46.             if val=='L':
  47.                 if i-1>=0 and d[i-1]=='.':
  48.                     d[i-1]='L'
  49.                     q.append((i-1,'L'))
  50.             elif val=='R':
  51.                 if i+1<n and d[i+1]=='.':
  52.                     if i+2<n and d[i+2]=='L':
  53.                         q.popleft()
  54.                     else:
  55.                         d[i+1]='R'
  56.                         q.append((i+1,'R'))
  57.         return ''.join(d)
Add Comment
Please, Sign In to add comment