Skip to main content
Back to problems
#2120
Medium Algorithms

Execution of all suffix instructions staying in a grid

String Simulation
82.0% acceptance
Feb 25, 2026
566
54
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] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn execute_instructions(n: i32, start_pos: Vec<i32>, s: String) -> Vec<i32> {
    let s: Vec<u8> = s.bytes().collect();
    let m = s.len();
    let mut ans = vec![0i32; m];

    for i in 0..m {
      let (mut r, mut c) = (start_pos[0], start_pos[1]);
      let mut count = 0;
      for &instr in &s[i..] {
        let (dr, dc) = match instr {
          b'L' => (0, -1),
          b'R' => (0, 1),
          b'U' => (-1, 0),
          b'D' => (1, 0),
          _ => (0, 0),
        };
        let nr = r + dr;
        let nc = c + dc;
        if nr < 0 || nr >= n || nc < 0 || nc >= n {
          break;
        }
        r = nr;
        c = nc;
        count += 1;
      }
      ans[i] = count;
    }
    ans
  }
}