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
Focus on handling base cases like empty input and prefix invalid cases to avoid trivial failures.
Implement cycle detection and ensure full DFS postorder traversal to handle complex graph structures.
Optimize your solution to linear time complexity by avoiding nested loops and using adjacency lists.
t1_01basic
Input["wrt","wrf","er","ett","rftt"]
Expected"wertf"
⏱ Performance - must finish in 2000ms
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'.
💡 Build a graph of character precedence from adjacent words.
💡 Use DFS postorder traversal to perform topological sort on the graph.
💡 Return the reversed postorder traversal as the character order.
Why it failed: Incorrect output means graph construction or DFS order is wrong. Fix by ensuring edges are added only for first differing characters and DFS postorder is reversed.
✓ Correctly infers character order using DFS postorder topological sort.
t1_02basic
Input["z","x"]
Expected"zx"
⏱ Performance - must finish in 2000ms
Only two words with different first characters 'z' and 'x', so 'z' < 'x'.
💡 Check the first differing character between adjacent words to build edges.
💡 Ensure single character words are handled correctly in graph.
💡 DFS postorder should produce 'z' before 'x' in the output.
Why it failed: If output is reversed or missing characters, DFS postorder or graph edges are incorrect. Fix by reversing DFS postorder and adding all unique chars.
✓ Correctly handles simple two-word input with direct precedence.
t2_01edge
Input[]
Expected""
⏱ Performance - must finish in 2000ms
Empty input list means no characters, so output is empty string.
💡 Consider what happens if input list is empty.
💡 No words means no characters to order.
💡 Return empty string immediately if input is empty.
Why it failed: Returning non-empty string on empty input means missing base case. Fix by checking if words list is empty and return "".
✓ Correctly returns empty string for empty input.
t2_02edge
Input["abc"]
Expected"abc"
⏱ Performance - must finish in 2000ms
Single word input means order is all unique characters in that word in order.
💡 With only one word, no precedence edges exist.
💡 All characters appear with zero in-degree.
💡 Return characters in the order they appear in the single word.
Why it failed: If output is empty or unordered, code misses single word case or does not include all chars. Fix by adding all unique chars even if no edges.
✓ Correctly returns all unique characters in single word input.
t2_03edge
Input["abc","ab"]
Expected""
⏱ Performance - must finish in 2000ms
Prefix word longer than next word with same prefix is invalid order, so output empty string.
💡 Check if a longer word appears before its prefix word.
💡 This violates lexicographical order in alien dictionary.
💡 Return empty string if prefix condition is violated.
Why it failed: If output is non-empty, code misses prefix invalid case. Fix by checking prefix condition and returning "" if violated.
✓ Correctly detects invalid prefix order and returns empty string.
t2_04edge
Input["abc","def"]
Expected"abcdef"
⏱ Performance - must finish in 2000ms
No edges inferred since first characters differ and no order constraints beyond that; output concatenates all unique chars.
💡 When no edges exist, output all unique characters in any order.
💡 DFS postorder traversal will include all nodes with zero in-degree.
💡 Ensure all unique characters are included in output.
Why it failed: If output misses characters or is empty, code does not include all unique chars. Fix by adding all unique chars to graph and output.
✓ Correctly outputs all unique characters when no order constraints.
t3_01corner
Input["abc","bca","cab"]
Expected""
⏱ Performance - must finish in 2000ms
Cycle exists in character order: a < b, b < c, c < a, so no valid order.
💡 Detect cycles in the graph using DFS visitation states.
💡 If a node is visited twice in the current DFS path, a cycle exists.
💡 Return empty string if cycle detected.
Why it failed: If output is non-empty, cycle detection is missing or incorrect. Fix by adding DFS cycle detection with recursion stack.
✓ Correctly detects cycle and returns empty string.
t3_02corner
Input["za","zb","ca","cb"]
Expected"zacb"
⏱ Performance - must finish in 2000ms
Multiple disconnected components: 'z' < 'c' inferred from order of words, output concatenates components in valid order.
💡 Build graph with multiple disconnected components.
💡 Topological sort should include all components in order.
💡 DFS postorder traversal concatenates all components correctly.
Why it failed: If output misses characters or orders components incorrectly, graph traversal or initialization is wrong. Fix by including all unique chars and traversing all nodes.
Greedy approach might fail by assuming first differing char order only; correct DFS postorder handles multiple edges properly.
💡 Check all edges from first differing characters between adjacent words.
💡 DFS postorder ensures correct order even with multiple edges.
💡 Avoid greedy assumptions; rely on full graph traversal.
Why it failed: If output is incorrect or partial, greedy approach used instead of full DFS topological sort. Fix by implementing DFS postorder topological sort.
✓ Correctly handles multiple edges and complex order with DFS.
t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
Expectednull
⏱ 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.
💡 Use adjacency list and efficient graph construction.
💡 DFS postorder topological sort runs in linear time O(C + U + E).
💡 Avoid nested loops over all pairs of words to prevent TLE.
Why it failed: TLE indicates brute force or inefficient graph construction. Fix by using adjacency list and DFS topological sort with linear complexity.
✓ Algorithm runs within time limit using efficient DFS topological sort.
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
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.
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.
Final Answer:
Option A -> Option A
Quick Check:
Leaf trimming is the known optimal pattern for Minimum Height Trees [OK]
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
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.
Step 2: Consequence of bug
This causes incorrect topo_order and potentially infinite loops or wrong dp updates.
Final Answer:
Option C -> Option C
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
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.
Step 2: Understand impact of missing check
Without returning [0] for single-node tree, the function returns incorrect empty result.
Final Answer:
Option A -> Option A
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
Step 1: Understand reuse impact on matrix construction
Allowing reuse means elements can appear multiple times, so positions must reflect frequency, not just order.
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.
Final Answer:
Option C -> Option C
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
Step 1: Understand repeated courses and prerequisites
Allowing repeated courses with prerequisites means cycles can form because a course depends on itself indirectly.