Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2120: Execution of All Suffix Instructions Staying in a Grid

In this guide, we solve Leetcode #2120 Execution of All Suffix Instructions Staying in a Grid in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: String, Simulation

Intuition

We need to scan characters while tracking positions or counts.

A simple state machine keeps the logic precise.

Approach

Iterate through the string once and update the state for each character.

Use a map or array if you need fast lookups.

Steps:

  • Iterate through characters.
  • Maintain necessary state.
  • Build or validate the output.

Example

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.

Python Solution

class Solution: def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]: ans = [] m = len(s) mp = {"L": [0, -1], "R": [0, 1], "U": [-1, 0], "D": [1, 0]} for i in range(m): x, y = startPos t = 0 for j in range(i, m): a, b = mp[s[j]] if 0 <= x + a < n and 0 <= y + b < n: x, y, t = x + a, y + b, t + 1 else: break ans.append(t) return ans

Complexity

The time complexity is O(n). The space complexity is O(1) to O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy