From 42d2162c388fc782e029f542742e23db0d65d24d Mon Sep 17 00:00:00 2001 From: RamKuppagiri Date: Sat, 21 Feb 2026 10:08:45 -0600 Subject: [PATCH] Graph-1 solutions --- findJudge.js | 22 ++++++++++++++++++++++ hasPath.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 findJudge.js create mode 100644 hasPath.js diff --git a/findJudge.js b/findJudge.js new file mode 100644 index 0000000..d9fab1c --- /dev/null +++ b/findJudge.js @@ -0,0 +1,22 @@ +/** +Intuition: +Treat each person’s score as +1 when someone trusts them, and −1 when they trust someone else. +The town judge trusts nobody and is trusted by everyone else (n−1 times +1), so their final score must be n − 1. +Compute these scores and return the person whose score equals n − 1, otherwise return −1. +T.C: O(V+E) +S.C: O(V) + */ +var findJudge = function (n, trust) { + let inOrder = new Array(n).fill(0); + + for (let [i, j] of trust) { + inOrder[i - 1]--; + inOrder[j - 1]++; + } + + for (let idx = 0; idx < inOrder.length; idx++) { + if (inOrder[idx] === n - 1) return idx + 1; + } + + return -1; +}; \ No newline at end of file diff --git a/hasPath.js b/hasPath.js new file mode 100644 index 0000000..0bcb08c --- /dev/null +++ b/hasPath.js @@ -0,0 +1,36 @@ +/** +Intuition: +Use BFS to explore the maze from the start position, treating each stopping point (where the ball hits a wall) as a node. +From each cell, roll in all four directions until hitting a wall, then step back to the last valid position. +If we ever stop exactly at the destination, return true; otherwise continue until all reachable positions are visited. +T.C: O(m*n) +S.C: O(m*n) + */ +var hasPath = function (maze, start, destination) { + let queue = [start]; + let rowLength = maze.length; + let colLength = maze[0].length; + // four directions + const directions = [[0, 1], [1, 0], [-1, 0], [0, -1]]; + while (queue.length) { + const [r, c] = queue.shift(); + maze[r][c] = 2; + for (let [i, j] of directions) { + let newR = r + i; + let newC = c + j; + while (newR >= 0 && newC >= 0 && newR < rowLength && newC < colLength && maze[newR][newC] != 1) { + newR = newR + i; + newC = newC + j; + } + // decrement to retrieve the last location before the wall or out of bounce. + newR -= i; + newC -= j; + //dest check + if (newR === destination[0] && newC === destination[1]) return true; + if (maze[newR][newC] !== 2) { + queue.push([newR, newC]); + } + } + } + return false; +}; \ No newline at end of file