#838

Push Dominoes

Medium
Two PointersStringDynamic ProgrammingTwo PointersDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass through the dominoes to determine the final state. We track the influence of 'R' and 'L' using a counter, allowing us to efficiently determine the final state of each domino.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an array to hold the final state of the dominoes.
  2. 2Step 2: Traverse the string and use a counter to track the influence of 'R' and 'L'.
  3. 3Step 3: Update the final state based on the counter values, determining if a domino falls left, right, or stays upright.
solution.py19 lines
1def pushDominoes(dominoes):
2    n = len(dominoes)
3    forces = [0] * n
4    for i in range(n):
5        if dominoes[i] == 'R':
6            forces[i] = 1
7        elif dominoes[i] == 'L':
8            forces[i] = -1
9    for i in range(1, n):
10        forces[i] += forces[i - 1]
11    result = []
12    for force in forces:
13        if force > 0:
14            result.append('R')
15        elif force < 0:
16            result.append('L')
17        else:
18            result.append('.')
19    return ''.join(result)

Complexity note: This complexity is linear because we only make a constant number of passes over the dominoes, and the space complexity is linear due to the additional array used to track forces.

  • 1Dominoes pushed from both sides will remain upright.
  • 2The influence of 'R' and 'L' can be tracked using a counter.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.