Bird
Raised Fist0
Interview Preptopological-sorthardAmazonGoogle

Longest Path With Different Adjacent Characters

Choose your preparation mode4 modes available
📋
Problem

Imagine you are designing a workflow system where each task depends on others, and you want to find the longest sequence of tasks where no two adjacent tasks share the same category.

Given a directed acyclic graph (DAG) with n nodes labeled from 0 to n-1, and a string s of length n where s[i] represents the character label of node i, find the length of the longest path in the graph such that no two adjacent nodes on the path have the same character. The graph is given as a list of edges, where each edge is a pair [u, v] indicating a directed edge from node u to node v. Return the length of the longest valid path. If the graph contains a cycle, return -1.

1 ≤ n ≤ 10^50 ≤ edges.length ≤ 10^5edges[i].length == 20 ≤ edges[i][0], edges[i][1] < ns consists of lowercase English lettersThe graph may be disconnected
Edge cases: Graph with no edges → longest path is 1 (single node)Graph with all nodes having the same character → longest path is 1Graph with multiple disconnected components → consider longest path in any component
</>
IDE
def longest_path_with_diff_adj_chars(n: int, edges: list[list[int]], s: str) -> int:public int longestPathWithDiffAdjChars(int n, int[][] edges, String s)int longestPathWithDiffAdjChars(int n, vector<vector<int>>& edges, string s)function longestPathWithDiffAdjChars(n, edges, s)
def longest_path_with_diff_adj_chars(n, edges, s):
    # Write your solution here
    pass
class Solution {
    public int longestPathWithDiffAdjChars(int n, int[][] edges, String s) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int longestPathWithDiffAdjChars(int n, vector<vector<int>>& edges, string s) {
    // Write your solution here
    return 0;
}
function longestPathWithDiffAdjChars(n, edges, s) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Returning 0 for single node or empty edge graph instead of 1.✅ Return 1 when n >= 1 even if edges are empty.
Wrong: 4Ignoring character difference constraint and counting path with same adjacent chars.✅ Add condition to skip edges where s[u] == s[v].
Wrong: Positive number instead of -1Missing cycle detection, causing infinite recursion or incorrect path length.✅ Implement cycle detection using DFS states or topological sort; return -1 if cycle found.
Wrong: Less than correct longest pathGreedy approach picking only one child or not considering all paths.✅ Use DP to consider all children and pick max path length.
Wrong: Incorrect due to revisiting nodes or cyclesConfusing 0/1 path with unbounded or revisiting nodes in DAG.✅ Use memoization or topological order to avoid revisiting nodes.
✓
Test Cases
t1_01basic
Input{"n":5,"edges":[[0,1],[1,2],[2,3],[3,4]],"s":"abaca"}
Expected3

One longest path is 0 -> 1 -> 2 with characters 'a', 'b', 'a'. Adjacent characters differ, length is 3.

t1_02basic
Input{"n":4,"edges":[[0,1],[1,2],[2,3]],"s":"abcd"}
Expected4

All characters differ along the path 0->1->2->3, so longest path length is 4.

t2_01edge
Input{"n":1,"edges":[],"s":"a"}
Expected1

Single node graph with no edges; longest path is 1.

t2_02edge
Input{"n":3,"edges":[[0,1],[1,2]],"s":"aaa"}
Expected1

All nodes have the same character; no two adjacent nodes can be on the path, so longest path is 1.

t2_03edge
Input{"n":4,"edges":[],"s":"abcd"}
Expected1

Graph with no edges; longest path is 1 (any single node).

t3_01corner
Input{"n":3,"edges":[[0,1],[1,2],[2,0]],"s":"abc"}
Expected-1

Graph contains a cycle (0->1->2->0), so return -1.

t3_02corner
Input{"n":5,"edges":[[0,1],[0,2],[1,3],[2,3],[3,4]],"s":"ababa"}
Expected4

Longest path is 0->1->3->4 or 0->2->3->4 with alternating characters, length 4.

t3_03corner
Input{"n":4,"edges":[[0,1],[1,2],[2,3]],"s":"abca"}
Expected4

Longest path 0->1->2->3 with characters 'a','b','c','a' all different adjacent pairs, length 4.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

Input size n=100000 with up to 100000 edges; solution must run in O(n + m) time within 2 seconds.

Practice

(1/5)
1. Consider the following code snippet implementing the optimal solution for the largest color value in a directed graph. Given colors = "abaca" and edges = [[0,1],[0,2],[2,3],[3,4]], what is the value of max_color_value after processing all nodes?
easy
A. 3
B. 4
C. 2
D. 5

Solution

  1. Step 1: Trace dp for node 0 (color 'a')

    dp[0]['a'] = 1, max_color_value = 1
  2. Step 2: Propagate to nodes 1 and 2

    Node 1 (color 'b'): dp[1]['a'] = 1, dp[1]['b'] = 1; Node 2 (color 'a'): dp[2]['a'] = 2, max_color_value = 2
  3. Step 3: Propagate to node 3 (color 'c')

    dp[3]['a'] = 2, dp[3]['c'] = 1, max_color_value = 2
  4. Step 4: Propagate to node 4 (color 'a')

    dp[4]['a'] = 3, max_color_value = 3
  5. Final Answer:

    Option A -> Option A
  6. Quick Check:

    Maximum color count along path is 3 for 'a' [OK]
Hint: Track dp updates per node carefully [OK]
Common Mistakes:
  • Off-by-one in dp increments or max updates
2. Consider the following Python code implementing the optimal leaf trimming approach for Minimum Height Trees. Given n = 4 and edges = [[1,0],[1,2],[1,3]], what is the final returned list?
easy
A. [3]
B. [0, 2, 3]
C. [2]
D. [1]

Solution

  1. Step 1: Initialize graph and degrees

    Nodes: 0,1,2,3; edges connect 1 to 0,2,3. Degrees: 0->1, 1->3, 2->1, 3->1. Leaves initially: [0,2,3].
  2. Step 2: Trim leaves until ≤ 2 nodes remain

    Remove leaves [0,2,3], decrement neighbors' degrees. Node 1 degree reduces from 3 to 0, becomes leaf. Remaining nodes = 4 - 3 = 1. Loop ends. Return [1].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Only node 1 remains as centroid after trimming [OK]
Hint: Leaves trimmed until ≤2 nodes remain [OK]
Common Mistakes:
  • Returning initial leaves
  • Off-by-one in loop
  • Not updating degrees correctly
3. What is the time complexity of the optimal DFS postorder topological sort approach for sequence reconstruction, given n as the length of the original sequence and m as the total length of all sequences in seqs?
medium
A. O(n + m)
B. O(n! * m)
C. O(n * m)
D. O(m^2)

Solution

  1. Step 1: Identify graph construction cost

    Building graph from seqs takes O(m) time, where m is total length of all sequences.
  2. Step 2: Analyze DFS traversal cost

    DFS visits each node once and edges once, total O(n + m). No extra factorial or quadratic factors.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Linear time in nodes plus edges [OK]
Hint: DFS topo sort is O(V+E) -> O(n+m) here [OK]
Common Mistakes:
  • Confusing with brute force factorial complexity
  • Assuming quadratic due to nested loops
4. Suppose the problem is modified so that nodes can be revisited multiple times (cycles allowed). Which modification to the iterative DFS approach is necessary to correctly find all paths from source to target without infinite loops?
hard
A. Add a visited set per path to prevent revisiting nodes already in the current path
B. Remove path tracking and rely on global visited set to avoid cycles
C. Use BFS instead of DFS to guarantee shortest paths and avoid cycles
D. No modification needed; the current approach handles cycles correctly

Solution

  1. Step 1: Identify cycle problem

    Allowing revisits means cycles can cause infinite loops if not tracked per path.
  2. Step 2: Solution approach

    Maintain a visited set per path to avoid revisiting nodes already in the current path, preventing cycles.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Global visited set disallows legitimate different paths; per-path visited set is needed [OK]
Hint: Cycle detection requires per-path visited tracking, not global visited [OK]
Common Mistakes:
  • Using global visited set incorrectly
  • Assuming no cycles without checks
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