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: empty string when valid order existsIncorrect cycle detection or premature return on partial graph.✅ Implement full graph traversal and only return empty string if a cycle is confirmed after processing all nodes.
Wrong: incorrect order with reversed edgesEdges added in wrong direction (e.g., w2[j] -> w1[j] instead of w1[j] -> w2[j]).✅ Add edge from first differing character in earlier word to that in later word: graph[w1[j]].add(w2[j])
Wrong: non-empty string for prefix invalid caseMissing check for prefix condition where longer word precedes its prefix.✅ Add explicit check: if len(w1) > len(w2) and w1.startswith(w2): return ""
Wrong: missing characters in outputNot including all unique characters in graph nodes or output if disconnected.✅ Initialize graph nodes for all unique characters and include them in topological sort output.
Wrong: TLE on large inputsUsing DFS with exponential complexity or inefficient graph representation.✅ Use Kahn's algorithm with adjacency list and in-degree array for O(C) complexity.
✓
Test Cases
Focus on handling empty inputs and prefix invalid cases to avoid base case bugs.
Test your cycle detection and ensure your topological sort includes all characters.
Optimize your solution to linear time using Kahn's algorithm to pass large inputs.
t1_01basic
Input["wrt","wrf","er","ett","rftt"]
Expected"wertf"
⏱ Performance - must finish in 2000ms
From 'wrt' and 'wrf', we know 't' < 'f'. From 'wrt' and 'er', 'w' < 'e'. From 'er' and 'ett', 'r' < 't'. From 'ett' and 'rftt', 'e' < 'r'. Combining these gives the order 'w', 'e', 'r', 't', 'f'.
💡 Compare adjacent words to find the first differing character to build ordering edges.
💡 Use topological sort (DFS or Kahn's algorithm) on the graph of characters to find a valid order.
💡 Detect cycles by tracking visiting states; return empty string if a cycle is found.
Why it failed: Incorrect output means the graph edges or cycle detection is wrong. Fix by ensuring edges are added only for first differing chars and cycle detection uses correct visited states.
✓ Correctly derived the alien alphabet order using graph construction and topological sort.
t1_02basic
Input["z","x"]
Expected"zx"
⏱ Performance - must finish in 2000ms
Only two words 'z' and 'x' imply 'z' < 'x' in the alien alphabet.
💡 With only two words, compare their first characters to find ordering.
💡 Build graph with edge from 'z' to 'x' and perform topological sort.
💡 Return the order of unique characters respecting the edge.
Why it failed: If output is empty or reversed, likely failed to add edge for first differing characters or reversed edge direction. Fix by adding edge from first word's char to second word's char.
✓ Correctly handled minimal input with two words and derived order.
t2_01edge
Input[]
Expected""
⏱ Performance - must finish in 2000ms
Empty input means no words, so no characters and empty order.
💡 Check if input list is empty and handle as a special case.
💡 Return empty string if no words are given.
💡 Avoid processing graph or sorting when input is empty.
Why it failed: Returning non-empty string or error means missing empty input check. Fix by returning "" immediately if words list is empty.
✓ Correctly handled empty input by returning empty string.
t2_02edge
Input["a"]
Expected"a"
⏱ Performance - must finish in 2000ms
Single word with one character means order is that character.
💡 For single word, order is all unique characters in that word.
💡 No edges to build, so return the characters as is.
💡 Ensure to include all unique chars even if no ordering info.
Why it failed: If output is empty or missing characters, likely failed to handle single word input. Fix by returning all unique characters when only one word is given.
✓ Correctly returned single character order for single word input.
t2_03edge
Input["abc","ab"]
Expected""
⏱ Performance - must finish in 2000ms
Prefix case where second word is prefix of first is invalid, so return empty string.
💡 Check if a longer word appears before its prefix in the list.
💡 If prefix condition violated, no valid order exists.
💡 Return empty string immediately when prefix invalid detected.
Why it failed: If output is non-empty, failed to detect prefix invalid case. Fix by checking if w1 starts with w2 and w1 longer, then return "".
✓ Correctly detected invalid prefix ordering and returned empty string.
t2_04edge
Input["aaa","aaa","aaa"]
Expected"a"
⏱ Performance - must finish in 2000ms
All words identical means order is all unique chars in any order; here only 'a'.
💡 When all words are identical, no ordering edges exist.
💡 Return all unique characters present in the words.
💡 Ensure output includes all unique chars even if no edges.
Why it failed: If output is empty or missing characters, likely failed to include unique chars when no edges. Fix by collecting all unique chars and returning them.
✓ Correctly handled all identical words by returning unique characters.
t3_01corner
Input["abc","bcd","cde"]
Expected"abcde"
⏱ Performance - must finish in 2000ms
Linear chain ordering with no cycles; order is 'a' < 'b' < 'c' < 'd' < 'e'.
💡 Check that your topological sort does not greedily pick nodes without considering all edges.
💡 Ensure all edges are included and cycle detection is correct.
💡 Use Kahn's algorithm or DFS with proper visited states to get correct order.
Why it failed: If output is missing characters or order is incorrect, likely greedy approach picking nodes too early. Fix by using full topological sort with in-degree or DFS with cycle detection.
✓ Correctly handled linear chain ordering without greedy mistakes.
t3_02corner
Input["za","zb","ca","cb"]
Expected"zacb"
⏱ Performance - must finish in 2000ms
Multiple valid orders possible; one valid order is 'z' < 'a' < 'c' < 'b'.
💡 Handle cases where some characters have no direct ordering edges.
💡 Include all unique characters in the output even if disconnected.
💡 Use topological sort that includes all nodes, not just those with edges.
Why it failed: If output misses characters or returns empty string, likely failed to include all unique chars or handle disconnected graph. Fix by initializing graph nodes for all chars and including them in topological sort.
✓ Correctly included all characters and handled disconnected graph components.
t3_03corner
Input["abc","acd","bca"]
Expected""
⏱ Performance - must finish in 2000ms
Input contains a cycle in ordering, so no valid order exists; return empty string.
💡 Detect cycles in the graph using DFS visiting states or in-degree counts.
💡 Return empty string if cycle detected to indicate invalid ordering.
💡 Ensure cycle detection is robust for complex graphs.
Why it failed: If output is non-empty, cycle detection is missing or incorrect. Fix by marking nodes as visiting and detecting back edges during DFS or checking if topological sort includes all nodes.
✓ Correctly detected cycle and returned empty string.
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 and edges requires O(C) time topological sort to complete within 2 seconds.
💡 Use efficient graph building with adjacency lists and in-degree arrays.
💡 Apply Kahn's algorithm for topological sort to achieve O(C) time complexity.
💡 Avoid DFS recursion stack overflow and redundant edge insertions.
Why it failed: TLE indicates use of exponential or inefficient approach like naive DFS with repeated work. Fix by implementing Kahn's algorithm with proper data structures for O(C) complexity.
✓ Algorithm runs in O(C) time and handles large input efficiently.
Practice
(1/5)
1. You need to transform one string into another using the minimum number of insertions, deletions, and substitutions. Which algorithmic approach guarantees finding the optimal solution efficiently?
easy
A. Greedy algorithm that replaces characters whenever they differ
B. Pure brute force recursion without memoization
C. Dynamic Programming that builds a table of subproblem solutions based on prefixes
D. Divide and conquer by splitting strings into halves and solving independently
Solution
Step 1: Understand problem requires minimum edits
The problem asks for minimum insertions, deletions, and substitutions to convert one string to another, which is a classic DP problem.
Dynamic Programming builds solutions for prefixes and combines them, ensuring optimality and polynomial time.
Final Answer:
Option C -> Option C
Quick Check:
DP table approach is standard for edit distance [OK]
Hint: Edit distance requires DP over prefixes [OK]
Common Mistakes:
Thinking greedy or divide-and-conquer works optimally
2. You are given an array representing the heights of adjacent bars in a histogram. The task is to find the largest rectangular area that can be formed within the bounds of the histogram bars. Which algorithmic approach guarantees an optimal O(n) time solution for this problem?
easy
A. Greedy approach selecting the tallest bar and expanding outwards
B. Brute force nested loops checking all possible rectangles
C. Dynamic programming with memoization of subproblems
D. Single pass stack-based approach that tracks indices of bars
Solution
Step 1: Understand problem constraints and requirements
The problem requires finding the largest rectangle in a histogram efficiently, which involves checking contiguous bars and their heights.
Step 2: Identify optimal approach using stack
The single pass stack-based approach uses a stack to keep track of indices of bars in ascending order, allowing calculation of maximal rectangle areas in O(n) time by popping bars when a smaller height is encountered.
Final Answer:
Option D -> Option D
Quick Check:
Stack approach is known optimal for largest rectangle in histogram [OK]
Hint: Stack-based approach achieves O(n) time [OK]
Common Mistakes:
Assuming brute force is efficient enough
Confusing this with a DP problem
Thinking greedy expansion from tallest bar suffices
3. Examine the following code snippet for computing the maximum path sum in a binary tree. Which line contains a subtle bug that can cause incorrect results?
medium
A. Line where left gain is assigned without max(..., 0)
B. Line where helper returns node.val + max(left, right)
C. Line where max_sum is updated with node.val + left + right
D. Line with base case returning 0 for null nodes
Solution
Step 1: Identify that left and right gains must ignore negative sums by using max(helper(...), 0).
Without max(..., 0), negative subtree sums reduce the path sum incorrectly.
Step 2: Notice that line assigning left = helper(node.left) lacks max(..., 0), causing negative gains to propagate.
This leads to suboptimal max_sum updates and incorrect return values.
Final Answer:
Option A -> Option A
Quick Check:
Ignoring negative gains is a common subtle bug [OK]
Hint: Negative subtree sums must be zeroed out [OK]
Common Mistakes:
Not ignoring negative gains
Returning sum of both children to parent
Missing base case for null nodes
4. Suppose the problem is modified so that elements from the lists can be reused multiple times in the range (i.e., the range must cover at least one element from each list, but elements can be counted multiple times). Which modification to the optimal two-pointer approach is necessary to correctly solve this variant?
hard
A. Use a min-heap to always pick the smallest current element from each list and update the maximum accordingly.
B. No modification needed; the original two-pointer approach works as is.
C. Track counts of elements but do not decrement counts when moving the left pointer to allow reuse.
D. Enumerate all combinations with replacement and select the minimal range.
Solution
Step 1: Understand reuse impact
Allowing reuse means elements can be counted multiple times, so sliding window coverage logic breaks.
Step 2: Identify suitable approach
Min-heap approach maintains current smallest elements from each list and updates max to find minimal range, handling reuse correctly.
Final Answer:
Option A -> Option A
Quick Check:
Min-heap approach is standard for reuse variant [OK]
5. Suppose the skyline problem is extended so that buildings can overlap and have negative heights (representing underground structures). Which modification to the divide and conquer algorithm is necessary to correctly handle this variant?
hard
A. No modification needed; the existing merge logic works for negative heights
B. Modify the merge step to consider absolute values of heights when computing max height
C. Use a brute force height map simulation instead, as divide and conquer cannot handle negative heights
D. Adjust the merge step to track both max and min heights at each x-coordinate and merge accordingly
Solution
Step 1: Understand negative height impact
Negative heights mean skyline can go below ground, so max height alone is insufficient.
Step 2: Modify merge logic
Need to track both max and min heights to merge skylines correctly, handling positive and negative overlaps.
Step 3: Evaluate options
Ignoring negative heights or using absolute values breaks correctness; brute force is inefficient.
Final Answer:
Option D -> Option D
Quick Check:
Tracking both max and min heights handles negative overlaps correctly [OK]
Hint: Negative heights require tracking min as well as max heights [OK]
Common Mistakes:
Assuming negative heights can be handled as positive
Ignoring negative heights in merge logic
Switching to brute force unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.