Skip to main content

Largest Color Value in a Directed Graph - Solution & Explanation

HardHash TableDynamic ProgrammingGraphTopological Sort16 min readAsked at: Amazon, Meta, Google +2
Practice this problem

Problem Statement

There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.

You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.

A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.

Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.

 

Example 1:

Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image).

Example 2:

Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.

 

Constraints:

  • n == colors.length
  • m == edges.length
  • 1 <= n <= 105
  • 0 <= m <= 105
  • colors consists of lowercase English letters.
  • 0 <= aj, bj < n

Approach Overview

Problem Overview: You receive a directed graph where every node has a color. The goal is to find the largest number of occurrences of a single color along any valid path. If the graph contains a cycle, the answer must be -1 because paths can grow infinitely.

Approach 1: Topological Sort with Kahn's Algorithm and Color Frequency Tracking (O((V+E)*26) time, O(V*26) space)

This approach treats the problem as dynamic programming over a DAG. First build an adjacency list and compute the in-degree of each node. Using topological sort (Kahn's algorithm), process nodes with in-degree 0. For every node, maintain an array of size 26 representing the maximum count of each color seen along paths ending at that node. When visiting a node, increment the count for its own color, then propagate the updated counts to its neighbors using max updates. If the number of processed nodes is less than n, a cycle exists and the result is -1. This method efficiently combines graph traversal with dynamic programming to track color frequencies.

Approach 2: DFS with Cycle Detection and Memoization (O((V+E)*26) time, O(V*26) space)

This strategy uses depth‑first search to explore paths while detecting cycles using a recursion stack. For each node, maintain a memoized color-frequency vector describing the best counts achievable from that node downward. During DFS, mark nodes as visiting to detect back edges (cycles). If a cycle is found, return -1. Otherwise compute the best color counts by combining results from all neighbors and incrementing the current node’s color. Memoization prevents recomputation of subgraphs and ensures each node is processed once.

Recommended for interviews: The topological sort solution is the most common interview expectation because it explicitly handles cycle detection and processes nodes in dependency order. DFS with memoization demonstrates deeper graph reasoning and is also accepted, but candidates usually reach the Kahn's algorithm approach faster. Showing awareness of cycle detection and maintaining a 26‑length color frequency array is the key insight.

Approach 1: Topological Sort with Kahn's Algorithm and Color Frequency Tracking

This approach leverages a topological sort using Kahn's algorithm to process nodes in an order that respects the directed edges. We use an additional data structure to keep a running tally of the frequency of each color at every node, and update these tallies as we process nodes. This allows us to track the most frequently occurring color for all paths.

If we detect any cycles during this process, we can immediately return -1.

The implementation starts by constructing an adjacency list from the edges and calculates the in-degree for each node. We use Kahn's algorithm to perform a topological sort, starting with nodes with zero in-degree.

During the processing, we maintain a color frequency table for each node, updating the table as we process each node's neighbors. If the node count at the end doesn't match the number of nodes, a cycle exists, and we return -1. Otherwise, we return the maximum color frequency value found.

Code

Python

Java

Complexity

Time Complexity: O(n + m), where n is the number of nodes and m is the number of edges. This accounts for the initial processing of nodes and edges and the BFS traversal of the graph.

Space Complexity: O(n), mainly due to the adjacency list, in-degree array, and color count table.

Try this approach in the editor →

Approach 2: DFS with Cycle Detection and Memoization

This approach applies a Depth-First Search (DFS) on each node while using memoization to store and retrieve previously computed results. This aids in finding the most frequent color along paths derived from each node.

During DFS, we also check for cycles by marking nodes as currently being visited, immediately returning -1 upon detecting a cycle.

The C++ solution utilizes DFS to explore paths from all nodes. During exploration, if a node is detected as currently being visited, it indicates a cycle, and we return -1.

A memoization table stores the frequency of colors for paths from each node. After processing all nodes, the highest frequency from the table is the desired result.

Code

C++

JavaScript

Complexity

Time Complexity: O(n + m), for processing nodes, edges, and DFS traversal.

Space Complexity: O(n), driven by memoization and state tracking.

Try this approach in the editor →

Approach 3: Topological Sort + Dynamic Programming

Calculate the in-degree of each node and perform a topological sort.

Define a 2D array dp, where dp[i][j] represents the number of nodes with color j on the path from the start node to node i.

From node i, traverse all outgoing edges i \to j, and update dp[j][k] = max(dp[j][k], dp[i][k] + (c == k)), where c is the color of node j.

The answer is the maximum value in the dp array.

If there is a cycle in the graph, it is impossible to visit all nodes, so return -1.

The time complexity is O((n + m) times |\Sigma|), and the space complexity is O(m + n times |\Sigma|). Here, |\Sigma| is the size of the alphabet (26 in this case), and n and m are the number of nodes and edges, respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Topological Sort with Kahn's Algorithm and Color Frequency Tracking

Time Complexity: O(n + m), where n is the number of nodes and m is the number of edges. This accounts for the initial processing of nodes and edges and the BFS traversal of the graph.

Space Complexity: O(n), mainly due to the adjacency list, in-degree array, and color count table.

DFS with Cycle Detection and Memoization

Time Complexity: O(n + m), for processing nodes, edges, and DFS traversal.

Space Complexity: O(n), driven by memoization and state tracking.

Topological Sort + Dynamic Programming—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Topological Sort with Color Frequency DPO((V+E)*26)O(V*26)Best general solution for directed graphs with cycle detection and path DP
DFS with Memoization and Cycle DetectionO((V+E)*26)O(V*26)Useful when solving with recursive graph traversal and caching results

Video Solution

Largest Color Value in a Directed Graph - Leetcode 1857 - Python • NeetCodeIO • 33,653 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Largest Color Value in a Directed Graph easy or hard?
Largest Color Value in a Directed Graph is classified as a Hard problem. The challenge comes from combining cycle detection with dynamic programming on graph paths while efficiently tracking color frequencies. Understanding topological ordering or DFS memoization is essential to reach the optimal solution.
Largest Color Value in a Directed Graph Python/Java solution
Most implementations use Kahn's algorithm with a queue and a 2D array of size n x 26. Python typically uses collections.deque for the queue and lists for color counts, while Java uses ArrayDeque and int arrays. Both versions maintain dynamic programming states while processing nodes in topological order.
How to solve Largest Color Value in a Directed Graph in O(n)?
The problem can be solved in linear graph time using topological sorting with dynamic programming. Build the adjacency list, compute in-degrees, and process nodes using a queue. For each node maintain a 26-element array of color frequencies and update neighbors using max comparisons. The runtime becomes O((V+E)*26), which is effectively linear relative to the graph size.
What is the best approach for Largest Color Value in a Directed Graph?
Topological sort using Kahn's algorithm combined with dynamic programming is the most reliable approach. Each node maintains a 26-length array tracking the maximum frequency of each color along paths reaching it. Processing nodes in topological order guarantees dependencies are resolved and also allows easy cycle detection. The complexity is O((V+E)*26).
Is Largest Color Value in a Directed Graph asked at Google/Amazon/Meta?
Graph DP and topological sort problems like this frequently appear in interviews at companies such as Google, Amazon, and Meta. The question tests cycle detection, DAG processing, and dynamic programming on graphs. Variants of this problem are common in senior backend and infrastructure interview rounds.
What data structure is used in Largest Color Value in a Directed Graph?
Key data structures include an adjacency list to represent the directed graph, a queue for Kahn's topological sort, and a 2D array or list storing color frequencies for each node. DFS implementations also use recursion stacks and memoization tables to detect cycles and cache results.
What is the time complexity of Largest Color Value in a Directed Graph?
The optimal solutions run in O((V+E)*26) time, where V is the number of nodes and E is the number of edges. The factor 26 comes from tracking counts for each lowercase English letter. Space complexity is O(V*26) to store color frequency information for every node.

Ready to solve this problem?

Practice Largest Color Value in a Directed Graph with our built-in code editor and test cases.

Practice on FleetCode