diff --git a/FindtheTownJudge.java b/FindtheTownJudge.java new file mode 100644 index 0000000..e47859a --- /dev/null +++ b/FindtheTownJudge.java @@ -0,0 +1,26 @@ +/* +* Approach: +- There are two properties to become a town judge. + - town judge trusts nobody + - everybody trusts town judge +- So we can iterate through the trust list, and decrement the count of the person who is trusting somebody and incremeent the count of someone who is being trusted +- once that is down, if we find at any index the count is equal to total number people - 1, then they can be a town judge +TC: O(v+e) -> v to iterate over all the trust list and e to iterate over the edges +SC: O(n) -> array to store in and out degrees of each person +*/ +class Solution { + public int findJudge(int n, int[][] trust) { + int[] indeg = new int[n+1]; + //count the in and out degrees + for(int[] tr: trust){ + indeg[tr[0]]--; + indeg[tr[1]]++; + } + //check if any person is being trust by everyone except themselves + for(int i = 1; i < n + 1; i++){ + if(indeg[i] == n - 1) + return i; + } + return -1; + } +} \ No newline at end of file diff --git a/TheMaze.java b/TheMaze.java new file mode 100644 index 0000000..618be0f --- /dev/null +++ b/TheMaze.java @@ -0,0 +1,46 @@ +/* +* Approach1: BFS (Connected Components) +- The idea is to start from the starting coordinate and keep moving in whichever direction possible. +- But we are not just stopping at the neighbour and adding that to the queue, we want to check where the wall is in that direction, because the ball will not stop until it hits the wall +- Once the ball hits the wall, the cell before that is where the ball will stop and explore other possible direction, so we need to make sure we take the step back and if that cell is the destination, then return true +- Also, if we move passed the destination and the ball didnt stop, we should not immediately return false because ball can reach the destination from multiple directions so we dont return false, until we have explored all the paths from which the ball can reach the destination +- TC: O(m*n) - because the each cell is explored once and as the visited nodes increases, the traversal decreases +-SC: O(m*n) - for maintaining the queue (queue of where teh ball stops and not the neighbours) +*/ +class Solution { + public boolean hasPath(int[][] maze, int[] start, int[] destination) { + if(maze == null || maze.length == 0){ + return false; + } + int m = maze.length; + int n = maze[0].length; + int[][] dirs = new int[][]{{-1,0},{1,0}, {0,1}, {0,-1}}; + Queue q = new LinkedList<>(); + q.add(start); + maze[start[0]][start[1]] = 2; + //O(m*n) + while(!q.isEmpty()){ + int[] curr = q.poll(); + //put the babies + for(int[] dir: dirs){ + int r = curr[0]; + int c = curr[1]; + while(r < m && r>= 0 && c>=0 && c