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

grid47
grid47
Exploring patterns and algorithms
Apr 9, 2024 6 min read

You are given an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). A robot starts at a given position startPos = [startrow, startcol] on the grid, and a string s representing a sequence of movement instructions: ‘L’ (move left), ‘R’ (move right), ‘U’ (move up), and ‘D’ (move down). The robot can execute the instructions starting from any index i in s, but it stops if it moves off the grid or runs out of instructions. Your task is to return an array answer where answer[i] represents the number of instructions the robot can execute if it starts from the ith instruction.
Problem
Approach
Steps
Complexity
Input: You are given the size of the grid n, the starting position startPos, and a string s of instructions.
Example: n = 3, startPos = [0, 1], s = 'RRDDLU'
Constraints:
• 1 <= n, m <= 500
• startPos.length == 2
• 0 <= startrow, startcol < n
• s consists of 'L', 'R', 'U', and 'D'.
Output: Return an array of integers where each element at index i represents the number of instructions that can be executed if the robot begins at the ith instruction in the sequence.
Example: For n = 3, startPos = [0, 1], s = 'RRDDLU', the output is [1, 5, 4, 3, 1, 0].
Constraints:
Goal: To determine how many instructions the robot can execute starting from each index in the instruction string while staying within the bounds of the grid.
Steps:
• For each instruction in the string s, simulate the robot's movement starting from that position, tracking the number of valid moves.
• Stop the simulation if the robot moves off the grid or there are no more instructions to process.
• Store the number of valid instructions the robot can execute starting from each index and return the result.
Goal: The solution must work efficiently for the maximum input size.
Steps:
• The grid size n and the instruction string length m are both capped at 500.
Assumptions:
• The robot will always start within the bounds of the grid.
Input: Example 1: n = 3, startPos = [0, 1], s = 'RRDDLU'
Explanation: Starting from the initial position (0, 1), the robot can execute the following instructions starting from each index: 1 move from index 0 ('R'), 5 moves from index 1 ('RDDLU'), and so on.

Input: Example 2: n = 2, startPos = [1, 1], s = 'LURD'
Explanation: From position (1, 1), the robot can execute the following instructions starting from each index: 4 moves from index 0 ('LURD'), 1 move from index 1 ('URD'), and so on.

Input: Example 3: n = 1, startPos = [0, 0], s = 'LRUD'
Explanation: Since the grid is of size 1x1, no moves can be executed, and the result is [0, 0, 0, 0].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus