#2120

Execution of All Suffix Instructions Staying in a Grid

Medium
StringSimulationSimulationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a single pass from the end of the instruction string to the beginning, calculating how many instructions can be executed from each index. This way, we can build the answer array in linear time by leveraging previously computed results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an answer array of the same length as the instruction string, filled with zeros.
  2. 2Step 2: Start from the last instruction and move backwards to the first instruction.
  3. 3Step 3: For each instruction, check if the robot can move in the specified direction and update the position and count accordingly.
solution.py23 lines
1# Full working Python code
2
3def executeInstructions(n, startPos, s):
4    m = len(s)
5    answer = [0] * m
6    x, y = startPos
7    for i in range(m - 1, -1, -1):
8        if i < m - 1:
9            answer[i] = answer[i + 1]
10        if s[i] == 'L':
11            y -= 1
12        elif s[i] == 'R':
13            y += 1
14        elif s[i] == 'U':
15            x -= 1
16        elif s[i] == 'D':
17            x += 1
18        if 0 <= x < n and 0 <= y < n:
19            answer[i] += 1
20        else:
21            break
22    return answer
23

Complexity note: The time complexity is O(n) because we only make a single pass through the instruction string, and the space complexity is O(n) due to the answer array.

  • 1The robot's movement can be efficiently simulated by processing the instructions in reverse.
  • 2Using previously computed results can help avoid redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.