Leetcode 838: Push Dominoes

grid47
grid47
Exploring patterns and algorithms
Aug 15, 2024 7 min read

In a line of n dominoes, each domino is initially standing upright. Some dominoes are pushed either to the left or the right. Over time, falling dominoes will cause adjacent dominoes to fall in the same direction. If a domino is pushed from both sides, it remains standing. The task is to simulate the final state of the dominoes after all the forces are applied.
Problem
Approach
Steps
Complexity
Input: You are given a string representing the initial state of the dominoes. Each character in the string is one of 'L', 'R', or '.' representing a domino that has been pushed to the left, right, or is still standing upright, respectively.
Example: Input: dominoes = 'R..L.'
Constraints:
• 1 <= n <= 10^5
• dominoes[i] is one of 'L', 'R', or '.'
Output: Return a string representing the final state of the dominoes after all forces have been applied.
Example: Output: 'RRLL.'
Constraints:
• The output string should have the same length as the input string.
Goal: Simulate the effect of the falling dominoes and determine the final state of the line of dominoes.
Steps:
• Step 1: Add a 'L' at the start and an 'R' at the end of the input string to handle edge cases.
• Step 2: Iterate through the string and determine the state of each domino after forces from both sides are applied.
• Step 3: Use a sliding window approach to determine how the forces affect the dominoes in between.
• Step 4: Return the final string representing the state of the dominoes.
Goal: Ensure that the input and output meet the provided constraints for string length and valid characters.
Steps:
• The input string length must be between 1 and 10^5.
• The characters in the string must be 'L', 'R', or '.' as described.
Assumptions:
• Dominoes falling to the left will push adjacent dominoes to the left.
• Dominoes falling to the right will push adjacent dominoes to the right.
• If a domino has forces applied from both sides, it remains upright.
Input: Input: 'R..L.'
Explanation: Here, the first domino is pushed to the right and the last domino is pushed to the left. The dominoes in between are stationary but will be affected by the falling forces from both sides. The final state is 'RRLL.'

Input: Input: 'R.L.'
Explanation: In this case, the dominoes are pushed in opposite directions, and the falling forces cancel each other out in the middle. The final state remains as 'R.L.'

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus