Skip to content

Commit 96f5593

Browse files
authored
Create execution-of-all-suffix-instructions-staying-in-a-grid.py
1 parent b083bbb commit 96f5593

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(m)
2+
# Space: O(m)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def executeInstructions(self, n, startPos, s):
9+
"""
10+
:type n: int
11+
:type startPos: List[int]
12+
:type s: str
13+
:rtype: List[int]
14+
"""
15+
directions = {'U':(-1, 0), 'R':(0, 1), 'D':(1, 0), 'L':(0, -1)}
16+
(x0, y0), (x, y) = startPos, (0, 0)
17+
result = range(len(s), 0, -1)
18+
lookup_x = collections.defaultdict(list)
19+
lookup_y = collections.defaultdict(list)
20+
lookup_x[x0-x].append(0)
21+
lookup_y[y0-y].append(0)
22+
for i, d in enumerate(s):
23+
dx, dy = directions[d]
24+
x, y = x+dx, y+dy
25+
for k in n-x, -x-1:
26+
if k not in lookup_x:
27+
continue
28+
for j in lookup_x[k]:
29+
result[j] = min(result[j], i-j)
30+
lookup_x[k] = []
31+
for k in n-y, -y-1:
32+
if k not in lookup_y:
33+
continue
34+
for j in lookup_y[k]:
35+
result[j] = min(result[j], i-j)
36+
lookup_y[k] = []
37+
lookup_x[x0-x].append(i+1)
38+
lookup_y[y0-y].append(i+1)
39+
return result

0 commit comments

Comments
 (0)