Skip to content

Commit 22c3e54

Browse files
author
Joseph Luce
authored
Update Longest_movie_title.md
1 parent e179844 commit 22c3e54

File tree

1 file changed

+29
-19
lines changed

1 file changed

+29
-19
lines changed

real_interview_questions/Google/Longest_movie_title.md

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,21 @@ import copy
55
def concat_longest_title(titles):
66
adj_list = create_adj_list(titles)
77
global_visit = set()
8-
global_title = list()
8+
longest_title = list()
9+
memo = dict()
910
for title in adj_list.keys():
1011
if title not in global_visit:
1112
local_visit = set()
1213
local_title = list()
13-
visit_title(title,
14-
local_title,
15-
global_title,
16-
adj_list,
17-
local_visit,
18-
global_visit)
19-
return ' '.join(global_title)
14+
local_result = visit_title(title,
15+
local_title,
16+
adj_list,
17+
local_visit,
18+
global_visit,
19+
memo)
20+
if len(local_result) > len(longest_title):
21+
longest_title = copy.deepcopy(local_result)
22+
return longest_title
2023
2124
def create_adj_list(titles):
2225
firstWord_to_titles_hash = dict()
@@ -39,25 +42,32 @@ def create_adj_list(titles):
3942
result[title] = list()
4043
return result
4144
42-
def visit_title(title, stack, longest_title, adj_list, local_visit, global_visit):
43-
print longest_title
45+
def visit_title(title, stack, adj_list, local_visit, global_visit, memo):
46+
if title in memo:
47+
return memo[title]
4448
result = list()
4549
if title not in local_visit:
4650
local_visit.add(title)
4751
stack.append(title)
48-
if len(stack) > len(longest_title):
49-
longest_title = copy.deepcopy(stack)
5052
neighbors = adj_list[title]
5153
for next_title in neighbors:
52-
visit_title(next_title,
53-
stack,
54-
longest_title,
55-
adj_list,
56-
local_visit,
57-
global_visit)
54+
local_result = visit_title(next_title,
55+
stack,
56+
adj_list,
57+
local_visit,
58+
global_visit,
59+
memo)
60+
if len(local_result) > len(result):
61+
result = copy.deepcopy(local_result)
62+
if len(stack) > len(result):
63+
result = copy.deepcopy(stack)
5864
stack.pop()
65+
memo[title] = result
66+
return result
5967
6068
Input = ['OF MICE AND MEN', 'BLACK MASS', 'MEN IN BLACK']
61-
69+
Input = ['a b', 'b c', 'c d', 'c e', 'e f']
70+
Input = ['a b', 'b c', 'c a']
71+
6272
print concat_longest_title(Input)
6373
```

0 commit comments

Comments
 (0)