There are n dominoes in a line, represented as a string dominoes. Each character is:
'L' — this domino has been pushed to the left'R' — this domino has been pushed to the right'.' — this domino is standing stillSimultaneously, each domino that is falling pushes any adjacent standing domino in the same direction. If a vertical domino has dominoes falling on it from both sides, it stays still due to balanced forces.
Return a string representing the final state.
dominoes[i] is either 'L', 'R', or '.'Simulate each round of falling: apply forces from all currently-falling dominoes to their neighbors. Repeat until no changes occur. In the worst case this takes O(n) rounds of O(n) work each.
Why it's not optimal: Up to O(n) rounds × O(n) per round = O(n²). The two-pointer approach processes each pair of adjacent force points directly in O(n).
def pushDominoes(dominoes): state = list(dominoes) while True: new_state = state[:] for i in range(len(state)): if state[i] == '.': if i > 0 and state[i-1] == 'R': new_state[i] = 'R' elif i < len(state)-1 and state[i+1] == 'L': new_state[i] = 'L' if new_state == state: break state = new_state return ''.join(state)
Pad the string with sentinel 'L' on the left and 'R' on the right. Then scan for adjacent force points (dom[l], dom[r]) and deterministically fill the gap between them based on the four possible combinations.
dom = 'L' + dominoes + 'R'.r. Skip dots. When dom[r] is L or R, process the gap (l, r).
Discussion
…