Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Prashant Basnet
π Welcome to my Signature, a space between logic and curiosity.
Iβm a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and βahaβ moments that keep me building.
π Problem Restatement (in simpler terms)
You are given:
π§ What is a path?
A path is a sequence of nodes:
Now suppose the colors string is:
colors = "abaca" β so:
And your edges are:
Letβs pick a path:
On this path, the colors are:
So the color frequency for this path is:
β What this does imply:
β Example:
Letβs say:
Instead of tracking that whole path, you just do:
π§ Why not 1D array ?
β οΈ The core issue:
π§ͺ Example to show why 1D fails:
Letβs say:
Suppose two paths go to node 2:
But:
β Why 2D works:
π§ Analogy:
Think of it like tracking the highest GPA in every subject per student:
/** * @param {string} colors * @param {number[][]} edges * @return {number} */ var largestPathValue = function(colors, edges) { const n = colors.length const indegrees = new Array(n).fill(0) const graph = new Array(n).fill(0).map(o => []) const colorCounts = new Array(n).fill(0).map(o => new Array(26).fill(0)) let maxColorCode = 0for(let [prereq, course] of edges){ indegrees[course]++ graph[prereq].push(course) }const queue = [] for(let i = 0 ; i < indegrees.length; i++){ if(indegrees[i] === 0){ queue.push(i) } }function updateColorCode(node) { let colorIndex = colors.charCodeAt(node) - 97 colorCode[node][colorIndex]++ maxColorCode = Math.max(maxColorCode, colorCode[node][colorIndex]) }let visited = 0 while (0 < queue.length) { const node = queue.shift() visited++ updateColorCode(node) for (let neighbour of graph[node]) {for (let color = 0; color < 26; color++) { colorCounts[neighbour][color] = Math.max(colorCounts[neighbour][color], colorCounts[node][color]) }indegrees[neighbour]-- if (indegrees[neighbour] === 0) { queue.push(neighbour) } } }Final Space Complexity:
Because 26 is constant β drops out in Big-O notation.
Final Time Compelxity: