Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions findJudge.js
Original file line number Diff line number Diff line change
@@ -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;
};
36 changes: 36 additions & 0 deletions hasPath.js
Original file line number Diff line number Diff line change
@@ -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;
};