Bird
Raised Fist0
Interview Preptopological-sorthardFacebookAmazonGoogleBloomberg

Alien Dictionary (Infer Character Order)

Choose your preparation mode4 modes available
</>
IDE
def alienOrder(words: list[str]) -> str:public String alienOrder(String[] words)string alienOrder(vector<string> words)function alienOrder(words)
def alienOrder(words):
    # Write your solution here
    pass
class Solution {
    public String alienOrder(String[] words) {
        // Write your solution here
        return "";
    }
}
#include <vector>
#include <string>
using namespace std;

string alienOrder(vector<string> words) {
    // Write your solution here
    return "";
}
function alienOrder(words) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Partial or incomplete character order stringNot including all unique characters in the output, especially those with zero in-degree and no edges.✅ Initialize in-degree for all unique characters and include them in the final order even if they have no edges.
Wrong: Non-empty string when input has prefix invalid orderMissing check for prefix condition where a longer word appears before its prefix word.✅ Add explicit check: if len(w1) > len(w2) and w1 starts with w2, return empty string immediately.
Wrong: Non-empty string despite cycle in graphCycle detection missing or incorrect in DFS traversal.✅ Implement DFS visitation states (unvisited, visiting, visited) and return empty string if a cycle is detected.
Wrong: Incorrect order due to greedy approachAssuming first differing character order is sufficient without full graph traversal.✅ Use DFS postorder topological sort to get correct global order instead of greedy local decisions.
Wrong: TLE on large inputsUsing nested loops comparing all pairs of words or inefficient graph construction.✅ Build graph only from adjacent word pairs and use adjacency lists with DFS topological sort for O(C + U + E) complexity.
✓
Test Cases
t1_01basic
Input["wrt","wrf","er","ett","rftt"]
Expected"wertf"

From 'wrt' and 'wrf', infer 't' < 'f'. From 'wrt' and 'er', 'w' < 'e'. From 'er' and 'ett', 'r' < 't'. From 'ett' and 'rftt', 'e' < 'r'. Combined order is 'w', 'e', 'r', 't', 'f'.

t1_02basic
Input["z","x"]
Expected"zx"

Only two words with different first characters 'z' and 'x', so 'z' < 'x'.

t2_01edge
Input[]
Expected""

Empty input list means no characters, so output is empty string.

t2_02edge
Input["abc"]
Expected"abc"

Single word input means order is all unique characters in that word in order.

t2_03edge
Input["abc","ab"]
Expected""

Prefix word longer than next word with same prefix is invalid order, so output empty string.

t2_04edge
Input["abc","def"]
Expected"abcdef"

No edges inferred since first characters differ and no order constraints beyond that; output concatenates all unique chars.

t3_01corner
Input["abc","bca","cab"]
Expected""

Cycle exists in character order: a < b, b < c, c < a, so no valid order.

t3_02corner
Input["za","zb","ca","cb"]
Expected"zacb"

Multiple disconnected components: 'z' < 'c' inferred from order of words, output concatenates components in valid order.

t3_03corner
Input["abc","abd","abf"]
Expected"acdfb"

Greedy approach might fail by assuming first differing char order only; correct DFS postorder handles multiple edges properly.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 with total characters up to 10^6 requires O(C + U + E) DFS topological sort to complete within 2 seconds.

Practice

(1/5)
1. Given the following code implementing Kahn's Algorithm for course scheduling, what is the final output when calling findOrder(4, [[1,0],[2,0],[3,1],[3,2]])?
easy
A. [0, 1, 2, 3]
B. []
C. [3, 1, 2, 0]
D. [0, 2, 1, 3]

Solution

  1. Step 1: Initialize in-degree and queue

    In-degree: [0,1,1,2]; queue starts with [0] since only course 0 has in-degree 0.
  2. Step 2: Process queue and update order

    Pop 0 -> order=[0]; neighbors 1 and 2 in-degree decremented to 0 -> queue=[1,2]; pop 1 -> order=[0,1]; neighbor 3 in-degree decremented to 1; pop 2 -> order=[0,1,2]; neighbor 3 in-degree decremented to 0 -> queue=[3]; pop 3 -> order=[0,1,2,3].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Order respects prerequisites and includes all courses [OK]
Hint: Track in-degree updates and queue contents carefully [OK]
Common Mistakes:
  • Mixing order of nodes popped from queue
  • Forgetting to decrement in-degree
  • Returning empty list incorrectly
2. Consider the following code snippet implementing the optimal solution for the largest color value in a directed graph. Given colors = "abaca" and edges = [[0,1],[0,2],[2,3],[3,4]], what is the value of max_color_value after processing all nodes?
easy
A. 3
B. 4
C. 2
D. 5

Solution

  1. Step 1: Trace dp for node 0 (color 'a')

    dp[0]['a'] = 1, max_color_value = 1
  2. Step 2: Propagate to nodes 1 and 2

    Node 1 (color 'b'): dp[1]['a'] = 1, dp[1]['b'] = 1; Node 2 (color 'a'): dp[2]['a'] = 2, max_color_value = 2
  3. Step 3: Propagate to node 3 (color 'c')

    dp[3]['a'] = 2, dp[3]['c'] = 1, max_color_value = 2
  4. Step 4: Propagate to node 4 (color 'a')

    dp[4]['a'] = 3, max_color_value = 3
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Maximum color count along path is 3 for 'a' [OK]
Hint: Track dp updates per node carefully [OK]
Common Mistakes:
  • Off-by-one in dp increments or max updates
3. You are given a directed acyclic graph where each node has a character label. You want to find the longest path such that no two adjacent nodes on the path share the same character. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Greedy DFS that always picks the next node with a different character without backtracking
B. Simple DFS with memoization ignoring character constraints
C. Bellman-Ford algorithm treating characters as weights
D. Topological sort followed by iterative dynamic programming to compute longest valid paths

Solution

  1. Step 1: Understand problem constraints

    The problem requires finding longest paths in a DAG with an additional character adjacency constraint, which prevents naive longest path algorithms.
  2. Step 2: Identify suitable algorithm

    Topological sort linearizes the DAG, enabling dynamic programming to compute longest paths while enforcing character difference constraints efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Topological sort + DP handles DAG and character constraints correctly [OK]
Hint: Longest path in DAG with constraints -> topological sort + DP [OK]
Common Mistakes:
  • Assuming greedy DFS always works without backtracking
  • Ignoring character constraints in memoization
  • Using shortest path algorithms like Bellman-Ford incorrectly
4. If the problem is extended so that the same element can appear multiple times in the matrix (i.e., reuse allowed), which modification to the topological sort approach is necessary to correctly build the matrix?
hard
A. No change needed; reuse does not affect topological ordering
B. Replace topological sort with a longest path algorithm to handle repeated elements
C. Track counts of each element and assign positions based on frequency, not just order
D. Modify graph to allow self-loops and update cycle detection accordingly

Solution

  1. Step 1: Understand reuse impact on matrix construction

    Allowing reuse means elements can appear multiple times, so positions must reflect frequency, not just order.
  2. Step 2: Adjust algorithm to track counts and assign positions accordingly

    Topological order alone does not handle multiple occurrences; tracking counts and assigning positions based on frequency is necessary.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Frequency tracking ensures correct placement of repeated elements [OK]
Hint: Reuse implies tracking element counts and positions [OK]
Common Mistakes:
  • Assuming reuse needs no algorithm change
  • Ignoring frequency of elements
  • Replacing topological sort unnecessarily
5. Suppose the problem is modified so that some courses can be taken multiple times (repeatedly) and prerequisites must be satisfied each time before retaking. Which of the following statements about adapting the BFS topological sort approach is correct?
hard
A. We should switch to a dynamic programming approach because BFS topological sort cannot handle repeated courses.
B. The original BFS topological sort can be used without changes since it handles cycles by returning -1.
C. We can use BFS topological sort by resetting indegrees after each semester and reprocessing courses as needed.
D. The problem becomes invalid because repeated courses create cycles; BFS topological sort cannot be applied directly.

Solution

  1. Step 1: Understand repeated courses and prerequisites

    Allowing repeated courses with prerequisites means cycles can form because a course depends on itself indirectly.
  2. Step 2: Analyze BFS topological sort applicability

    BFS topological sort requires a DAG; cycles break this assumption, so it cannot be applied directly.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Repeated courses induce cycles -> BFS topological sort invalid [OK]
Hint: Repeated courses create cycles, breaking DAG assumption [OK]
Common Mistakes:
  • Assuming BFS topological sort handles cycles by returning -1
  • Thinking resetting indegrees can simulate repeats correctly
  • Believing DP is always needed without analyzing graph structure
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard