Bird
Raised Fist0
Interview Preptopological-sorthardGoogleAmazon

Largest Color Value in a Directed Graph

Choose your preparation mode4 modes available
</>
IDE
def largestPathValue(colors: str, edges: list[list[int]]) -> int:public int largestPathValue(String colors, int[][] edges)int largestPathValue(string colors, vector<vector<int>>& edges)function largestPathValue(colors, edges)
def largestPathValue(colors, edges):
    # Write your solution here
    pass
class Solution {
    public int largestPathValue(String colors, int[][] edges) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int largestPathValue(string colors, vector<vector<int>>& edges) {
    // Write your solution here
    return 0;
}
function largestPathValue(colors, edges) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: -1 on acyclic graphCycle detection incorrectly flags acyclic graphs as cyclic.✅ Use a 3-state visited array (0=unvisited,1=visiting,2=visited) to detect cycles precisely.
Wrong: 0 for single node graphBase case for single node not handled; DP arrays not initialized properly.✅ Initialize DP counts for each node's color to 1 at start.
Wrong: Value less than actual max color frequencyDP does not aggregate max counts correctly across all paths.✅ Update DP for each node by taking max over all predecessors for each color.
Wrong: Value greater than max color frequencyDouble counting nodes or unbounded counting bug.✅ Ensure each node counted once per path; no repeated counting in DP.
Wrong: TLE on large inputsExponential DFS or inefficient approach used.✅ Implement topological sort with DP for O(n + e) complexity.
✓
Test Cases
t1_01basic
Input{"colors":"abaca","edges":[[0,1],[0,2],[2,3],[3,4]]}
Expected3

The path 0 -> 2 -> 3 -> 4 has colors 'a', 'a', 'c', 'a'. The color 'a' appears 3 times, which is the largest color value.

t1_02basic
Input{"colors":"abcde","edges":[[0,1],[1,2],[2,3],[3,4]]}
Expected1

All nodes have distinct colors along the path 0->1->2->3->4, so max color frequency is 1.

t2_01edge
Input{"colors":"a","edges":[]}
Expected1

Single node with no edges; max color frequency is 1.

t2_02edge
Input{"colors":"","edges":[]}
Expected0

Empty graph (n=0); no nodes means max color value is 0.

t2_03edge
Input{"colors":"aaaaa","edges":[[0,1],[1,2],[2,3],[3,4]]}
Expected5

All nodes have the same color 'a' along a linear path of length 5; max color frequency is 5.

t2_04edge
Input{"colors":"abc","edges":[]}
Expected1

Multiple disconnected nodes with no edges; max color frequency is 1 for any single node.

t3_01corner
Input{"colors":"ab","edges":[[0,1],[1,0]]}
Expected-1

Graph contains a cycle between nodes 0 and 1; output must be -1.

t3_02corner
Input{"colors":"abcabc","edges":[[0,1],[1,2],[2,3],[3,4],[4,5]]}
Expected2

Longest path is 0->1->2->3->4->5 with colors 'a','b','c','a','b','c'. Max frequency is 2 for colors 'a','b', or 'c'.

t3_03corner
Input{"colors":"aabbcc","edges":[[0,1],[1,2],[2,3],[3,4],[4,5]]}
Expected2

Longest path 0->1->2->3->4->5 with colors 'a','a','b','b','c','c'. Max frequency is 2 for colors 'a','b', or 'c'.

t4_01performance
Input{"colors":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","edges":[]}
⏱ Performance - must finish in 2000ms

n=100 nodes with no edges; solution must run in O(n) time within 2 seconds.

Practice

(1/5)
1. Given the following code snippet implementing topological sort positions, what is the final value of the pos array after processing conditions = [[1,2],[1,3],[3,4]] with n=4?
easy
A. [0, 0, 1, 2, 3]
B. [0, 0, 2, 1, 3]
C. [0, 0, 1, 3, 2]
D. [0, 1, 2, 3, 0]

Solution

  1. Step 1: Initialize graph and in-degree arrays

    Edges: 1->2, 1->3, 3->4; in_degree: [0,0,1,1,1]
  2. Step 2: Process queue and assign positions

    Queue starts with node 1 (in_degree 0). Assign pos[1]=0. Decrement in_degree of 2 and 3 to 0, enqueue both. Next, dequeue 2 (pos[2]=1), then dequeue 3 (pos[3]=2), decrement in_degree of 4 to 0, enqueue 4, assign pos[4]=3.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Positions reflect valid topological order [OK]
Hint: Track in-degree and queue order carefully [OK]
Common Mistakes:
  • Swapping positions of nodes 2 and 3
  • Off-by-one indexing in pos array
2. Consider the following Python code implementing the optimal approach for minimum semesters. Given n = 3 and relations = [[1,3],[2,3]], what is the value of semester returned by the function?
from collections import deque, defaultdict

def min_semesters_optimal(n, relations):
    graph = defaultdict(list)
    indegree = [0] * (n + 1)
    for u, v in relations:
        graph[u].append(v)
        indegree[v] += 1

    queue = deque([i for i in range(1, n + 1) if indegree[i] == 0])
    semester = 0
    processed = 0

    while queue:
        semester += 1
        for _ in range(len(queue)):
            course = queue.popleft()
            processed += 1
            for nei in graph[course]:
                indegree[nei] -= 1
                if indegree[nei] == 0:
                    queue.append(nei)

    return semester if processed == n else -1

print(min_semesters_optimal(3, [[1,3],[2,3]]))
easy
A. 2
B. 1
C. 3
D. -1

Solution

  1. Step 1: Initialize graph and indegree

    Courses 1 and 2 have indegree 0, course 3 has indegree 2.
  2. Step 2: Process BFS levels

    Semester 1: process courses 1 and 2 (both indegree 0), decrement indegree of 3 twice -> indegree[3] becomes 0, add 3 to queue. Semester 2: process course 3.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two BFS levels -> 2 semesters [OK]
Hint: Courses with zero indegree processed per semester [OK]
Common Mistakes:
  • Counting each course as a separate semester
  • Off-by-one error in semester increment
  • Returning -1 incorrectly when all courses processed
3. The following code attempts to find eventual safe states using the reversed graph and Kahn's algorithm. Identify the line containing the subtle bug that causes incorrect results on some inputs.
from collections import deque

def eventualSafeNodes(graph):
    n = len(graph)
    reverse_graph = [[] for _ in range(n)]
    in_degree = [0] * n

    for u in range(n):
        for v in graph[u]:
            reverse_graph[v].append(u)
        in_degree[u] = len(graph[u])  # Bug fixed here

    queue = deque([i for i in range(n) if in_degree[i] == 0])
    safe = []

    while queue:
        node = queue.popleft()
        safe.append(node)
        for prev in reverse_graph[node]:
            in_degree[prev] -= 1
            if in_degree[prev] == 0:
                queue.append(prev)

    return sorted(safe)
medium
A. Line initializing queue with nodes having in_degree zero
B. Line appending u to reverse_graph[v]
C. Line decrementing in_degree[prev] inside the while loop
D. Line setting in_degree[v] = len(graph[u]) inside the outer loop

Solution

  1. Step 1: Identify in-degree assignment error

    In-degree should be assigned per node u, but the original code assigned in_degree[v] inside inner loop, overwriting multiple times incorrectly.
  2. Step 2: Correct assignment

    It should be in_degree[u] = len(graph[u]) after inner loop completes, not in_degree[v].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Incorrect in-degree causes wrong queue initialization and wrong safe nodes [OK]
Hint: In-degree must be assigned per node, not per neighbor [OK]
Common Mistakes:
  • Confusing in-degree and out-degree assignment
  • Assigning in-degree inside inner loop incorrectly
  • Misusing loop variables for in-degree
4. What is the time complexity of the optimal BFS-based topological sort algorithm for the Parallel Courses problem, given n courses and m prerequisite relations?
medium
A. O(n + m) because each node and edge is processed once in BFS
B. O(m^2) because updating indegrees requires scanning all edges repeatedly
C. O(n * m) because for each course you process all edges
D. O(n^2) because in the worst case all courses depend on all others

Solution

  1. Step 1: Analyze graph traversal

    Each course (node) is enqueued and dequeued at most once; each edge is visited once when decrementing indegree.
  2. Step 2: Combine node and edge processing

    Total operations proportional to number of nodes plus edges -> O(n + m).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Linear time in nodes and edges [OK]
Hint: Each edge and node processed once in BFS [OK]
Common Mistakes:
  • Assuming nested loops cause O(n*m)
  • Confusing indegree updates as repeated scans
  • Assuming dense graph means O(n^2) always
5. Suppose the input graph is no longer guaranteed to be a tree but can contain cycles. Which modification to the leaf trimming algorithm is necessary to correctly find minimum height roots?
hard
A. Use BFS from every node to find minimum height roots since leaf trimming fails on cycles.
B. Run the same leaf trimming algorithm; cycles do not affect the result.
C. Detect and remove cycles first by pruning edges until the graph becomes a tree, then apply leaf trimming.
D. Apply a topological sort to the graph and pick nodes with zero in-degree as roots.

Solution

  1. Step 1: Understand impact of cycles

    Leaf trimming relies on tree properties (acyclic). Cycles cause infinite loops or incorrect leaf identification.
  2. Step 2: Modify algorithm to handle cycles

    Detect cycles and remove edges to convert graph into a tree or forest, then apply leaf trimming to find centroids.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Cycle removal is prerequisite for leaf trimming correctness [OK]
Hint: Leaf trimming requires acyclic graphs [OK]
Common Mistakes:
  • Assuming leaf trimming works on cyclic graphs
  • Using BFS from every node inefficiently
  • Applying topological sort on undirected graph
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