Push Dominoes - Problem
Imagine you're looking at a line of n dominoes standing upright. Suddenly, some dominoes are pushed - some topple to the left (L), others to the right (R), while some remain upright (.).
Physics takes over! Each second, falling dominoes push their neighbors in the same direction. When a domino gets pushed from both sides with equal force, it stays perfectly balanced and upright.
Your mission: Given the initial state as a string where
Example:
Physics takes over! Each second, falling dominoes push their neighbors in the same direction. When a domino gets pushed from both sides with equal force, it stays perfectly balanced and upright.
Your mission: Given the initial state as a string where
'L' means pushed left, 'R' means pushed right, and '.' means upright, determine what the dominoes look like after they've all settled.Example:
"R.L" becomes "RRL" - the middle domino gets pushed right before the left force reaches it! Input & Output
example_1.py β Basic Example
$
Input:
dominoes = "RR.L"
βΊ
Output:
"RRR"
π‘ Note:
The first domino falls right, the second is already falling right, the third gets pushed right by the second domino before the fourth domino's leftward force can reach it.
example_2.py β Balanced Forces
$
Input:
dominoes = ".L.R...LR..L.."
βΊ
Output:
"LL.RR.LLRRLL.."
π‘ Note:
Multiple force interactions create various regions where dominoes fall left, right, or remain upright when forces balance.
example_3.py β No Forces
$
Input:
dominoes = "..."
βΊ
Output:
"..."
π‘ Note:
When no dominoes are initially pushed, they all remain upright.
Visualization
Tap to expand
Understanding the Visualization
1
Map the Forces
Identify all source points where dominoes are initially pushed
2
Calculate Right Waves
Compute how far rightward forces travel from each R
3
Calculate Left Waves
Compute how far leftward forces travel from each L
4
Find the Winners
At each position, the stronger force determines the final state
Key Takeaway
π― Key Insight: Instead of simulating time steps, calculate force strengths directly - rightward forces decrease with distance from R, leftward forces decrease with distance from L, and the stronger force wins at each position!
Time & Space Complexity
Time Complexity
O(n)
Two passes through the array, each taking O(n) time
β Linear Growth
Space Complexity
O(n)
Need arrays to store force values from both directions
β‘ Linearithmic Space
Constraints
- 1 β€ dominoes.length β€ 105
-
dominoes[i] is either
'L','R', or'.' - All dominoes fall at the same speed (1 position per second)
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code