Solving Leetcode Interviews in Seconds with AI: Push Dominoes
Introduction
In this blog post, we will explore how to solve the LeetCode problem "838" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string dominoes representing the initial state where: dominoes[i] = 'L', if the ith domino has been pushed to the left, dominoes[i] = 'R', if the ith domino has been pushed to the right, and dominoes[i] = '.', if the ith domino has not been pushed. Return a string representing the final state. Example 1: Input: dominoes = "RR.L" Output: "RR.L" Explanation: The first domino expends no additional force on the second domino. Example 2: Input: dominoes = ".L.R...LR..L.." Output: "LL.RR.LLRRLL.." Constraints: n == dominoes.length 1 <= n <= 105 dominoes[i] is either 'L', 'R', or '.'.
Explanation
Here's the breakdown of the approach, complexities, and the Python code:
Approach:
- Use a
forcesarray to store the net force acting on each domino. Right pushes contribute positive force, left pushes contribute negative force. - Iterate from left to right to calculate the cumulative force from right pushes.
- Iterate from right to left to calculate the cumulative force from left pushes.
- Based on the net force at each index, determine the final state of the domino.
- Use a
Complexity:
- Runtime: O(n), where n is the length of the
dominoesstring. - Storage: O(n)
- Runtime: O(n), where n is the length of the
Code
def pushDominoes(dominoes: str) -> str:
n = len(dominoes)
forces = [0] * n
# Calculate forces from left to right (right pushes)
force = 0
for i in range(n):
if dominoes[i] == 'R':
force = n
elif dominoes[i] == 'L':
force = 0
else:
force = max(0, force - 1)
forces[i] += force
# Calculate forces from right to left (left pushes)
force = 0
for i in range(n - 1, -1, -1):
if dominoes[i] == 'L':
force = n
elif dominoes[i] == 'R':
force = 0
else:
force = max(0, force - 1)
forces[i] -= force
# Determine the final state based on the net force
result = ""
for force in forces:
if force > 0:
result += 'R'
elif force < 0:
result += 'L'
else:
result += '.'
return result