|
| 1 | +<br> |
| 2 | +<detailsclass="hint-accordion"> |
| 3 | +<summary>Recommended Time & Space Complexity</summary> |
| 4 | +<p> |
| 5 | +You should aim for a solution with <code>O(N + V + E)</code> time and <code>O(V + E)</code> space, where <code>N</code> is the sum of the lengths of all the strings, <code>V</code> is the number of unique characters (vertices), and <code>E</code> is the number of edges. |
| 6 | +</p> |
| 7 | +</details> |
| 8 | + |
| 9 | +<br> |
| 10 | +<detailsclass="hint-accordion"> |
| 11 | +<summary>Hint 1</summary> |
| 12 | +<p> |
| 13 | +Can you think of this as a graph problem? Characters from <code>a</code> through <code>z</code> are nodes. What could the edges represent here? How can you create edges from the given words? Perhaps you should try comparing two adjacent words. |
| 14 | +</p> |
| 15 | +</details> |
| 16 | + |
| 17 | +<br> |
| 18 | +<detailsclass="hint-accordion"> |
| 19 | +<summary>Hint 2</summary> |
| 20 | +<p> |
| 21 | +The relative ordering of the characters can be treated as edges. For example, consider the words ordered as <code>["ape", "apple"]</code>. <code>"ape"</code> comes before <code>"apple"</code>, which indicates that <code>'e'</code> is a predecessor of <code>'p'</code>. Therefore, there is a directed edge <code>e -> p</code>, and this dependency should be valid across all the words. In this way, we can build an adjacency list by comparing adjacent words. Can you think of an algorithm that is suitable to find a valid ordering? |
| 22 | +</p> |
| 23 | +</details> |
| 24 | + |
| 25 | +<br> |
| 26 | +<detailsclass="hint-accordion"> |
| 27 | +<summary>Hint 3</summary> |
| 28 | +<p> |
| 29 | +We can use Topological Sort to ensure every node appears after its predecessor. Using DFS, we traverse the graph built from the adjacency list. A visited map tracks nodes in the current DFS path: <code>False</code> means not in the path, and <code>True</code> means in the path. If any DFS call returns <code>True</code>, it indicates a cycle and we return immediately. How do we extract the ordering from this DFS? |
| 30 | +</p> |
| 31 | +</details> |
| 32 | + |
| 33 | +<br> |
| 34 | +<detailsclass="hint-accordion"> |
| 35 | +<summary>Hint 4</summary> |
| 36 | +<p> |
| 37 | +When we visit a node and its children and don't find a cycle, we mark the node as <code>False</code> in the map and append it to the result, treating this as a post-order traversal. If we find a cycle, we return an empty string; otherwise, we return the result list. |
| 38 | +</p> |
| 39 | +</details> |