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
23 changes: 23 additions & 0 deletions Problem-1
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Time Complexity: O(m + n), m -> no. of trust relations, n -> no. of people
// Space Complexity: O(n)

// Keep track of the number of trusts for each person in an array
// If a person trusts someone decrement the count in array, increment when someone trusts that person
// Return the person with n count, else return -1

class Solution {
public int findJudge(int n, int[][] trust) {
int[] arr = new int[n+1];
for(int i = 0; i < trust.length; i++) {
arr[trust[i][0]]--;
arr[trust[i][1]]++;
}

// Check for town judge
for(int i = 1; i < n+1; i++) {
if(arr[i] == n-1)
return i;
}
return -1;
}
}
41 changes: 41 additions & 0 deletions Problem-2
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Time Complexity: O(m * n)
// Space Complexity: O(m * n)

// Start from the starting position and add it to the queue
// Use BFS to add all position where the ball can stop and each time change value to -1 to know it was visited
// If the destination cell is reach at any point return true, else return false

class Solution {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{start[0], start[1]});
maze[start[0]][start[1]] = -1;
int[][] dirs = {{0,1}, {1,0}, {0,-1}, {-1,0}};

while(!q.isEmpty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
int[] curr = q.poll();
for(int[] d : dirs) {
int r = curr[0] + d[0];
int c = curr[1] + d[1];
// Move in that direction till ball hits a wall
while(r >= 0 && r < maze.length && c >= 0 && c < maze[0].length && maze[r][c] != 1) {
r += d[0];
c += d[1];
}
r -= d[0];
c -= d[1];
// Check for destination cell
if(r == destination[0] && c == destination[1])
return true;
if(maze[r][c] != -1) {
q.add(new int[]{r, c});
maze[r][c] = -1;
}
}
}
}
return false;
}
}