Problem

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.

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

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12

![](https://assets.leetcode.com/uploads/2021/12/09/1.png)

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: "_**R**_ RDDLU". 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:     "_**L**_ U". 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

![](https://assets.leetcode.com/uploads/2021/12/09/2.png)

Input: n = 2, startPos = [1,1], s = "LURD"
Output: [4,1,0,0]
Explanation:
- 0th: "_**LURD**_ ".
- 1st:  "_**U**_ RD".
- 2nd:   "RD".
- 3rd:    "D".

Example 3

1
2
3
4
5
6

![](https://assets.leetcode.com/uploads/2021/12/09/3.png)

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'.

Solution

Method 1 – Simulation for Each Suffix

Intuition

For each suffix of the instruction string, simulate the robot’s movement step by step, stopping if it would move off the grid. Count how many instructions can be executed before stopping.

Approach

  1. For each starting index i in the instruction string:
    • Set the robot’s position to startPos.
    • For each instruction from i to the end:
      • Move the robot according to the instruction.
      • If the robot moves off the grid, break.
      • Otherwise, increment the count.
  2. Store the count for each starting index in the answer array.
  3. Return the answer array.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    vector<int> executeInstructions(int n, vector<int>& startPos, string s) {
        int m = s.size();
        vector<int> ans(m);
        for (int i = 0; i < m; ++i) {
            int x = startPos[0], y = startPos[1], cnt = 0;
            for (int j = i; j < m; ++j) {
                if (s[j] == 'L') y--;
                else if (s[j] == 'R') y++;
                else if (s[j] == 'U') x--;
                else x++;
                if (x < 0 || x >= n || y < 0 || y >= n) break;
                cnt++;
            }
            ans[i] = cnt;
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int[] executeInstructions(int n, int[] startPos, String s) {
        int m = s.length();
        int[] ans = new int[m];
        for (int i = 0; i < m; ++i) {
            int x = startPos[0], y = startPos[1], cnt = 0;
            for (int j = i; j < m; ++j) {
                char c = s.charAt(j);
                if (c == 'L') y--;
                else if (c == 'R') y++;
                else if (c == 'U') x--;
                else x++;
                if (x < 0 || x >= n || y < 0 || y >= n) break;
                cnt++;
            }
            ans[i] = cnt;
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def executeInstructions(self, n: int, startPos: list[int], s: str) -> list[int]:
        m = len(s)
        ans = [0] * m
        for i in range(m):
            x, y = startPos
            cnt = 0
            for j in range(i, m):
                if s[j] == 'L':
                    y -= 1
                elif s[j] == 'R':
                    y += 1
                elif s[j] == 'U':
                    x -= 1
                else:
                    x += 1
                if x < 0 or x >= n or y < 0 or y >= n:
                    break
                cnt += 1
            ans[i] = cnt
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
impl Solution {
    pub fn execute_instructions(n: i32, start_pos: Vec<i32>, s: String) -> Vec<i32> {
        let m = s.len();
        let s = s.as_bytes();
        let mut ans = vec![0; m];
        for i in 0..m {
            let (mut x, mut y) = (start_pos[0], start_pos[1]);
            let mut cnt = 0;
            for j in i..m {
                match s[j] as char {
                    'L' => y -= 1,
                    'R' => y += 1,
                    'U' => x -= 1,
                    _ => x += 1,
                }
                if x < 0 || x >= n || y < 0 || y >= n { break; }
                cnt += 1;
            }
            ans[i] = cnt;
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    executeInstructions(n: number, startPos: number[], s: string): number[] {
        const m = s.length;
        const ans: number[] = new Array(m).fill(0);
        for (let i = 0; i < m; ++i) {
            let [x, y] = startPos;
            let cnt = 0;
            for (let j = i; j < m; ++j) {
                if (s[j] === 'L') y--;
                else if (s[j] === 'R') y++;
                else if (s[j] === 'U') x--;
                else x++;
                if (x < 0 || x >= n || y < 0 || y >= n) break;
                cnt++;
            }
            ans[i] = cnt;
        }
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(m^2), where m is the length of the instruction string.
  • 🧺 Space complexity: O(m) for the answer array.