From 0e1b3d06479a889051491f593834798b1a7a3142 Mon Sep 17 00:00:00 2001 From: Meet Patel Date: Sun, 19 Oct 2025 19:32:18 -0700 Subject: [PATCH] Completed Graph-1, 2 problems --- find-the-town-judge.ts | 22 +++++++++++++++++ the-maze.ts | 56 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 find-the-town-judge.ts create mode 100644 the-maze.ts diff --git a/find-the-town-judge.ts b/find-the-town-judge.ts new file mode 100644 index 0000000..58753eb --- /dev/null +++ b/find-the-town-judge.ts @@ -0,0 +1,22 @@ +// Time complexity- O(n) +// Space complecity - O(n) +// to find the judge, we have to check if everyone person in town trusts judge and judge trusts no one +// we can iterate through the trust for each person and reduce count when person trust other persion +// once we have the trust count ready for each person in town, check if any persion is qualified to be judge by checking if trust value is equal to number of people in town +function findJudge(n: number, trust: number[][]): number { + const result = new Array(n + 1).fill(0); + + for (let [truster, trusted] of trust) { + // decrement score for truster (out-degree) + result[truster] -= 1; + // increase score for trusted (indegree) + result[trusted] += 1; + } + + // check is any member is trust of all the person in town + for (let i = 1; i < result.length; i++) { + // check for n-1, to exclude judge + if (result[i] == n - 1) return i; + } + return -1; +} diff --git a/the-maze.ts b/the-maze.ts new file mode 100644 index 0000000..57a66c1 --- /dev/null +++ b/the-maze.ts @@ -0,0 +1,56 @@ +// Time complexity- O(m*n), m= number of rows, n = number of columns +// Space complecity - O(m*n) +function hasPath( + maze: number[][], + start: number[], + destination: number[] +): boolean { + // return early if start and destination + if (start[0] == destination[0] && start[1] == destination[1]) return true; + const dirs = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + + // put the "start" in queue to process + const q = [start]; + // mark start as visited (using 2) + maze[start[0]][start[1]] = 2; + + while (q.length > 0) { + let [r, c] = q.shift(); + + // travel in all four direction untill we hit a wall + for (let [x, y] of dirs) { + let nr = r; + let nc = c; + + // roll the ball in direction [x, y] until it hits a wall (1) or a boundary + while ( + nr >= 0 && + nc >= 0 && + nr < maze.length && + nc < maze[0].length && + maze[nr][nc] != 1 + ) { + nr += x; + nc += y; + } + // backtrack one step to the valid stopping position (before the wall) + nr -= x; + nc -= y; + + // return early if we reached destination + if (nr == destination[0] && nc == destination[1]) return true; + + // if cell is not visited already, mark visited and push to queue to process + if (maze[nr][nc] != 2) { + q.push([nr, nc]); + maze[nr][nc] = 2; + } + } + } + return false; +}