Skip to content

Commit 310d4af

Browse files
authored
Create restore-the-array-from-adjacent-pairs.py
1 parent 685f8c3 commit 310d4af

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def restoreArray(self, adjacentPairs):
6+
"""
7+
:type adjacentPairs: List[List[int]]
8+
:rtype: List[int]
9+
"""
10+
adj = collections.defaultdict(list)
11+
for u, v in adjacentPairs:
12+
adj[u].append(v)
13+
adj[v].append(u)
14+
result = next([x, adj[x][0]] for x in adj if len(adj[x]) == 1)
15+
while len(result) != len(adjacentPairs)+1:
16+
result.append(adj[result[-1]][adj[result[-1]][0] == result[-2]])
17+
return result

0 commit comments

Comments
 (0)