[Leetcode] 838. Push Dominoes

whitehousechef·2025년 5월 5일

https://leetcode.com/problems/push-dominoes/description/?envType=daily-question&envId=2025-05-02

initial

So theres so many conditions to account if current idx is ./L/R. We wanna make the main logic as simple as possible and dont want to handle edge cases.

The mini trick is appending L to left and R to right of the initial string. and use 2 pointer approach of appending length of (right-left-1) of whatever logic. It is right-left-1 cuz we are appending the previous result at the current iteration of for loop

sol

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        ans=""
        dominoes = 'L'+dominoes+'R'
        left=0
        for right in range(1,len(dominoes)):
            if dominoes[right]=='.':
                continue
            mid = right-left-1
            if left:
                ans+=dominoes[left]
            if dominoes[left]==dominoes[right]:
                ans+=dominoes[left]*mid
            elif dominoes[left]=='L' and dominoes[right]=='R':
                ans+='.'*mid
            else:
                ans+='R'*(mid//2)+'.'*(mid%2)+'L'*(mid//2)
            left=right
        return ans

complexity

n time
n space

0개의 댓글