You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Return the longest movie title found by successively matching the last and first words in each title, joining to form new titles, given an array containing a list of movie titles.
3
+
4
+
```
5
+
For example:
6
+
Input: ['OF MICE AND MEN', 'BLACK MASS', 'MEN IN BLACK"]
7
+
Output: 'OF MICE AND MEN IN BLACK MASS'
8
+
9
+
Explanation:
10
+
'OF MICE AND MEN' and 'MEN IN BLACK' join to form 'OF MICE AND MEN IN BLACK'.
11
+
You could further join 'OF MICE AND MEN IN BLACK' wth 'BLACK MASS' to form 'OF MICE AND MEN IN BLACK MASS'.
2
12
```
3
-
import copy
13
+
14
+
# EXPLAINATION
15
+
This is another graph problem. Make an adjacent list for each title. You may need need a hash table to help you perform this, mainly a hash table with first word as the key and the title as the value.
16
+
17
+
Then create a method that goes through all the titles and performs a DFS. When using a DFS on a graph, you will need a stack/recursion to keep the current longest title found so far. For each neighbor, we will call a DFS and concat the result from that search to our title and check if that new result is better than our result found so far.
18
+
19
+
Also, we will need a different visited set for each DFS, this is to avoid cyclic searches and to avoid doing useless searches.
20
+
Say you have 'a b', 'b c', 'c d', 'd e'. If you begun your search at 'c d', you will get a result of 'c d d e'. 'c d' and 'd e' will be marked as visited but when you visit 'd e ' again, you should not begin a new DFS with this title. But for 'b c' or 'a b' its fine to start a new DFS search.
21
+
22
+
Worst case occurs when the titles you start your DFS search will always create the next smallest title. Therefore it would be O(n^2), where N is the number of titles.
23
+
24
+
You can avoid O(n^2) by using memoization. Therefore, you can get O(n). Also if there is a recursive solution, there will be a dp solution. You can also use your memoization as your global visited set in this case.
0 commit comments