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. You are given an undirected tree with n nodes. The task is to find all nodes that, when chosen as roots, produce trees with minimum height. Which algorithmic approach best guarantees an optimal solution for this problem?
easy
A. Iteratively remove leaf nodes layer by layer until 1 or 2 centroids remain.
B. Use dynamic programming to store subtree heights and combine results.
C. Run BFS/DFS from every node to calculate tree height and pick minimum roots.
D. Apply a greedy approach by always choosing the node with maximum degree as root.

Solution

  1. Step 1: Understand the problem structure

    The problem asks for nodes that minimize tree height when chosen as roots. This corresponds to finding centroids of the tree.
  2. Step 2: Identify the correct approach

    Iteratively trimming leaves (nodes with degree 1) layer by layer reduces the tree towards its centroids. This approach guarantees finding the minimum height roots efficiently.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Leaf trimming is the known optimal pattern for Minimum Height Trees [OK]
Hint: Leaf trimming finds centroids efficiently [OK]
Common Mistakes:
  • Thinking BFS from each node is efficient
  • Confusing DP with leaf trimming
  • Greedy max-degree node is incorrect
2. The following code attempts to find the longest path with different adjacent characters in a DAG. Identify the line containing the subtle bug that causes incorrect results on graphs with cycles or repeated characters.
medium
A. Line with 'for node in topo_order:' loop
B. Line with 'dp = [1] * n' initialization
C. Line with 'if indegree[nei] <= 0:' condition
D. Line with 'return max(dp)' statement

Solution

  1. Step 1: Analyze indegree decrement and queue append

    The condition 'if indegree[nei] <= 0:' incorrectly allows nodes with negative indegree to be enqueued multiple times, breaking topological order.
  2. Step 2: Consequence of bug

    This causes incorrect topo_order and potentially infinite loops or wrong dp updates.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct condition should be 'indegree[nei] == 0' to enqueue once [OK]
Hint: Check indegree condition carefully for cycle detection [OK]
Common Mistakes:
  • Using <= 0 instead of == 0 for indegree check
  • Ignoring character difference in dp update
  • Incorrect dp initialization
3. Examine the following code snippet for finding Minimum Height Trees. Which line contains a subtle bug that causes incorrect results on single-node trees?
medium
A. Missing explicit check for n == 1 at the start
B. Line initializing leaves with nodes of degree 1
C. Line decrementing remaining_nodes by leaves_count
D. Line updating degree[nei] after removing a leaf

Solution

  1. Step 1: Identify edge case handling

    The code lacks a special case for n=1, so leaves initialization is empty and the loop never runs, returning an empty list.
  2. Step 2: Understand impact of missing check

    Without returning [0] for single-node tree, the function returns incorrect empty result.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Single-node tree must be handled explicitly [OK]
Hint: Check for single-node tree before main logic [OK]
Common Mistakes:
  • Forgetting n=1 case
  • Incorrect leaves initialization
  • Not updating degrees properly
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