2120. Execution of All Suffix Instructions Staying in a Grid LeetCode Solution

In this guide, you will get 2120. Execution of All Suffix Instructions Staying in a Grid LeetCode Solution with the best time and space complexity. The solution to Execution of All Suffix Instructions Staying in a Grid problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Execution of All Suffix Instructions Staying in a Grid solution in C++
  4. Execution of All Suffix Instructions Staying in a Grid solution in Java
  5. Execution of All Suffix Instructions Staying in a Grid solution in Python
  6. Additional Resources
2120. Execution of All Suffix Instructions Staying in a Grid LeetCode Solution image

Problem Statement of Execution of All Suffix Instructions Staying in a Grid

There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n – 1, n – 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).
You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: ‘L’ (move left), ‘R’ (move right), ‘U’ (move up), and ‘D’ (move down).
The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met:

The next instruction will move the robot off the grid.
There are no more instructions left to execute.

See also  290. Word Pattern LeetCode Solution

Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.

Example 1:

Input: n = 3, startPos = [0,1], s = “RRDDLU”
Output: [1,5,4,3,1,0]
Explanation: Starting from startPos and beginning execution from the ith instruction:
– 0th: “RRDDLU”. Only one instruction “R” can be executed before it moves off the grid.
– 1st: “RDDLU”. All five instructions can be executed while it stays in the grid and ends at (1, 1).
– 2nd: “DDLU”. All four instructions can be executed while it stays in the grid and ends at (1, 0).
– 3rd: “DLU”. All three instructions can be executed while it stays in the grid and ends at (0, 0).
– 4th: “LU”. Only one instruction “L” can be executed before it moves off the grid.
– 5th: “U”. If moving up, it would move off the grid.

Example 2:

Input: n = 2, startPos = [1,1], s = “LURD”
Output: [4,1,0,0]
Explanation:
– 0th: “LURD”.
– 1st: “URD”.
– 2nd: “RD”.
– 3rd: “D”.

Example 3:

Input: n = 1, startPos = [0,0], s = “LRUD”
Output: [0,0,0,0]
Explanation: No matter which instruction the robot begins execution from, it would move off the grid.

Constraints:

m == s.length
1 <= n, m <= 500
startPos.length == 2
0 <= startrow, startcol < n
s consists of 'L', 'R', 'U', and 'D'.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

2120. Execution of All Suffix Instructions Staying in a Grid LeetCode Solution in C++

class Solution {
 public:
  vector<int> executeInstructions(int n, vector<int>& startPos, string s) {
    const int m = s.length();
    const int uMost = startPos[0] + 1;
    const int dMost = n - startPos[0];
    const int lMost = startPos[1] + 1;
    const int rMost = n - startPos[1];
    const unordered_map<char, pair<int, int>> moves{
        {'L', {0, -1}},
        {'R', {0, 1}},
        {'U', {-1, 0}},
        {'D', {1, 0}},
    };

    vector<int> ans(m);
    unordered_map<int, int> reachX{{0, m}};
    unordered_map<int, int> reachY{{0, m}};
    int x = 0;
    int y = 0;

    for (int i = m - 1; i >= 0; --i) {
      const auto& [dx, dy] = moves.at(s[i]);
      x -= dx;
      y -= dy;
      reachX[x] = i;
      reachY[y] = i;
      int out = INT_MAX;
      if (const auto it = reachX.find(x - uMost); it != reachX.cend())
        out = min(out, it->second);
      if (const auto it = reachX.find(x + dMost); it != reachX.cend())
        out = min(out, it->second);
      if (const auto it = reachY.find(y - lMost); it != reachY.cend())
        out = min(out, it->second);
      if (const auto it = reachY.find(y + rMost); it != reachY.cend())
        out = min(out, it->second);
      ans[i] = out == INT_MAX ? m - i : out - i - 1;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

2120. Execution of All Suffix Instructions Staying in a Grid LeetCode Solution in Java

class Solution {
  public int[] executeInstructions(int n, int[] startPos, String s) {
    final int m = s.length();
    final int uMost = startPos[0] + 1;
    final int dMost = n - startPos[0];
    final int lMost = startPos[1] + 1;
    final int rMost = n - startPos[1];
    Map<Character, Pair<Integer, Integer>> moves = new HashMap<>();
    moves.put('L', new Pair<>(0, -1));
    moves.put('R', new Pair<>(0, 1));
    moves.put('U', new Pair<>(-1, 0));
    moves.put('D', new Pair<>(1, 0));

    int[] ans = new int[m];
    Map<Integer, Integer> reachX = new HashMap<>();
    Map<Integer, Integer> reachY = new HashMap<>();
    reachX.put(0, m);
    reachY.put(0, m);
    int x = 0;
    int y = 0;

    for (int i = m - 1; i >= 0; --i) {
      Pair<Integer, Integer> pair = moves.get(s.charAt(i));
      final int dx = pair.getKey();
      final int dy = pair.getValue();
      x -= dx;
      y -= dy;
      reachX.put(x, i);
      reachY.put(y, i);
      final int out = Math.min(Math.min(reachX.getOrDefault(x - uMost, Integer.MAX_VALUE),
                                        reachX.getOrDefault(x + dMost, Integer.MAX_VALUE)),
                               Math.min(reachY.getOrDefault(y - lMost, Integer.MAX_VALUE),
                                        reachY.getOrDefault(y + rMost, Integer.MAX_VALUE)));
      ans[i] = out == Integer.MAX_VALUE ? m - i : out - i - 1;
    }

    return ans;
  }
}
// code provided by PROGIEZ

2120. Execution of All Suffix Instructions Staying in a Grid LeetCode Solution in Python

class Solution:
  def executeInstructions(
      self,
      n: int,
      startPos: list[int],
      s: str,
  ) -> list[int]:
    moves = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}
    m = len(s)
    uMost = startPos[0] + 1
    dMost = n - startPos[0]
    lMost = startPos[1] + 1
    rMost = n - startPos[1]

    ans = [0] * m
    reach = {(0, None): m, (None, 0): m}
    x = 0
    y = 0

    for i in reversed(range(m)):
      dx, dy = moves[s[i]]
      x -= dx
      y -= dy
      reach[(x, None)] = i
      reach[(None, y)] = i
      out = min(reach.get((x - uMost, None), math.inf),
                reach.get((x + dMost, None), math.inf),
                reach.get((None, y - lMost), math.inf),
                reach.get((None, y + rMost), math.inf))
      ans[i] = m - i if out == math.inf else out - i - 1

    return ans
# code by PROGIEZ

Additional Resources

See also  238. Product of Array Except Self LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.