Bird
Raised Fist0
Interview Prepchallenge-problemshardFacebookAmazonGoogleBloomberg

Alien Dictionary

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: 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
t1_01basic
Input["wrt","wrf","er","ett","rftt"]
Expected"wertf"

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'.

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

Only two words 'z' and 'x' imply 'z' < 'x' in the alien alphabet.

t2_01edge
Input[]
Expected""

Empty input means no words, so no characters and empty order.

t2_02edge
Input["a"]
Expected"a"

Single word with one character means order is that character.

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

Prefix case where second word is prefix of first is invalid, so return empty string.

t2_04edge
Input["aaa","aaa","aaa"]
Expected"a"

All words identical means order is all unique chars in any order; here only 'a'.

t3_01corner
Input["abc","bcd","cde"]
Expected"abcde"

Linear chain ordering with no cycles; order is 'a' < 'b' < 'c' < 'd' < 'e'.

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

Multiple valid orders possible; one valid order is 'z' < 'a' < 'c' < 'b'.

t3_03corner
Input["abc","acd","bca"]
Expected""

Input contains a cycle in ordering, so no valid order exists; return empty string.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ 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.

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

  1. 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.
  2. Step 2: Identify approach guaranteeing optimal substructure

    Dynamic Programming builds solutions for prefixes and combines them, ensuring optimality and polynomial time.
  3. Final Answer:

    Option C -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Option D -> Option D
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Option A -> Option A
  4. 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

  1. Step 1: Understand reuse impact

    Allowing reuse means elements can be counted multiple times, so sliding window coverage logic breaks.
  2. 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.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Min-heap approach is standard for reuse variant [OK]
Hint: Reuse breaks sliding window; min-heap handles dynamic coverage [OK]
Common Mistakes:
  • Assuming no change needed
  • Trying to fix counts without changing approach
  • Using brute force for large inputs
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

  1. Step 1: Understand negative height impact

    Negative heights mean skyline can go below ground, so max height alone is insufficient.
  2. Step 2: Modify merge logic

    Need to track both max and min heights to merge skylines correctly, handling positive and negative overlaps.
  3. Step 3: Evaluate options

    Ignoring negative heights or using absolute values breaks correctness; brute force is inefficient.
  4. Final Answer:

    Option D -> Option D
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard