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 find-the-town-judge.ts
Original file line number Diff line number Diff line change
@@ -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;
}
56 changes: 56 additions & 0 deletions the-maze.ts
Original file line number Diff line number Diff line change
@@ -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;
}