Bird
Raised Fist0

Given the following code snippet implementing the optimal iterative DP solution for longest path with different adjacent characters, what is the returned value for n=3, edges=[[0,1],[1,2]], and s="abc"?

easy🧾 Code Trace Q3 of Q15
Topological Sort - Longest Path With Different Adjacent Characters
Given the following code snippet implementing the optimal iterative DP solution for longest path with different adjacent characters, what is the returned value for n=3, edges=[[0,1],[1,2]], and s="abc"?
A1
B2
C3
D-1
Step-by-Step Solution
Solution:
  1. Step 1: Perform topological sort

    Order is [0,1,2] since edges are 0->1 and 1->2.
  2. Step 2: Compute dp values

    dp[0]=1; dp[1]=max(1,1+1)=2 since s[1]!=s[0]; dp[2]=max(1,2+1)=3 since s[2]!=s[1].
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Longest path length is 3 with distinct adjacent chars [OK]
Quick Trick: Check dp updates along topological order [OK]
Common Mistakes:
MISTAKES
  • Forgetting character difference condition
  • Incorrect topological order
Trap Explanation:
PITFALL
  • Candidates often forget to check character difference, leading to shorter path length.
Interviewer Note:
CONTEXT
  • Tests ability to trace DP updates and topological order correctness.
Master "Longest Path With Different Adjacent Characters" in Topological Sort

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Topological Sort Quizzes