Execution of All Suffix Instructions Staying in a Grid — LeetCode 2120 Python Solution
- Problem
- #2120
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The 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).
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:
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2120. Execution of All Suffix Instructions Staying in a Grid is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2120. Execution of All Suffix Instructions Staying in a Grid?
- LeetCode 2120. Execution of All Suffix Instructions Staying in a Grid is rated Medium on LeetCode.
- What topics does LeetCode 2120. Execution of All Suffix Instructions Staying in a Grid cover?
- LeetCode 2120. Execution of All Suffix Instructions Staying in a Grid is tagged String and Simulation on LeetCode.