MediumNo. 0838
Push Dominoes — LeetCode 838 Python Solution
- Pattern
- Two Pointers
- Topics
- Two Pointers, String, Dynamic Programming
- Reading time
- 5 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- dominoes = "RR.L"
- Output
- "RR.L"
- Explanation
- The first domino expends no additional force on the second domino.
Python solution
class Solution:
def pushDominoes(self, dominoes: str) -> str:
n = len(dominoes)
q = deque()
time = [-1] * n
force = defaultdict(list)
for i, f in enumerate(dominoes):
if f != '.':
q.append(i)
time[i] = 0
force[i].append(f)
ans = ['.'] * n
while q:
i = q.popleft()
if len(force[i]) == 1:
ans[i] = f = force[i][0]
j = i - 1 if f == 'L' else i + 1
if 0 <= j < n:
t = time[i]
if time[j] == -1:
q.append(j)
time[j] = t + 1
force[j].append(f)
elif time[j] == t + 1:
force[j].append(f)
return ''.join(ans)Complexity
- Time
- O(n) (after optional sort O(n log n))
- Space · auxiliary
- O(n), where n is the number of dominoes
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 838. Push Dominoes is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0005 | Longest Palindromic Substring | Medium |
| 0392 | Is Subsequence | Easy |
| 0647 | Palindromic Substrings | Medium |
| 2911 | Minimum Changes to Make K Semi-palindromes | Hard |
| 0845 | Longest Mountain in Array | Medium |
| 0028 | Find the Index of the First Occurrence in a String | Easy |
Frequently asked questions
- How hard is LeetCode 838. Push Dominoes?
LeetCode 838. Push Dominoes is rated Medium on LeetCode.
- What is the time complexity of LeetCode 838. Push Dominoes?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 838. Push Dominoes?
The Python solution on this page uses O(n), where n is the number of dominoes auxiliary space.
- What topics does LeetCode 838. Push Dominoes cover?
LeetCode 838. Push Dominoes is tagged Two Pointers, String and Dynamic Programming on LeetCode.