Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

838. Push Dominoes

Explanation:

To solve this problem, we can simulate the process of pushing dominoes by iterating through the input string. We keep track of the state of each domino as it falls based on its surroundings. We can handle three cases: when a domino is falling to the left, to the right, or it is stable.

  1. When a domino is falling to the left, we update its state to 'L' if it was '.' or 'R' before.
  2. When a domino is falling to the right, we update its state to 'R' if it was '.' or 'L' before.
  3. When a domino is stable, we leave it unchanged.

We maintain two pointers to keep track of the dominoes falling to the left and to the right. By iterating through the string, we update the state of each domino based on its surroundings. Finally, we return the updated string representing the final state of the dominoes.

  • Time complexity: O(n) where n is the length of the input string.
  • Space complexity: O(n) for storing the updated state of the dominoes.

:

class Solution {
    public String pushDominoes(String dominoes) {
        char[] doms = dominoes.toCharArray();
        int n = doms.length;
        int[] forces = new int[n];
        
        int force = 0;
        for (int i = 0; i < n; i++) {
            if (doms[i] == 'R') force = n;
            else if (doms[i] == 'L') force = 0;
            else force = Math.max(force - 1, 0);
            forces[i] += force;
        }
        
        force = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (doms[i] == 'L') force = n;
            else if (doms[i] == 'R') force = 0;
            else force = Math.max(force - 1, 0);
            forces[i] -= force;
        }
        
        StringBuilder sb = new StringBuilder();
        for (int f : forces) {
            sb.append(f > 0 ? 'R' : f < 0 ? 'L' : '.');
        }
        
        return sb.toString();
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.