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
18 changes: 18 additions & 0 deletions Find the Town Judge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Time Complexity : O(V + E) where V is the number of people and E is the number of realtionsips
# Space Complexity : O(V)
# Did this code successfully run on Leetcode : Yes
# Three line explanation of solution in plain english: We create an array having length equal to the number of people given. Everytime the person trusts somebody then we reduce the count by 1 and if the person is trusted by someone else we increase the count by 1. The index in the array having count 1 less than the total number of people will be the town judge.

class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
indegrees = [0] * (n + 1)

for tr in trust:
indegrees[tr[0]] -= 1
indegrees[tr[1]] += 1

for i in range(1, n + 1):
if indegrees[i] == n - 1:
return i

return -1
45 changes: 45 additions & 0 deletions The Maze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Time Complexity : O(m * n)
# Space Complexity : O(m * n)
# Did this code successfully run on Leetcode : Yes
# Three line explanation of solution in plain english: We use BFS to solve the problem. We traverse in one direction until we hit the stopping point. We make the stopping point equal to -1 to keep track that it has been visited.
import collections
class Solution:
def hasPath(self, maze, start, destination):
self.dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]]
self.m = len(maze)
self.n = len(maze[0])

q = collections.deque()
q.append([start[0], start[1]])
maze[start[0]][start[1]] = -1

while q:
curr = q.popleft()
for dir in self.dirs:
r = dir[0] + curr[0]
c = dir[1] + curr[1]

while r >= 0 and c >= 0 and r < self.m and c < self.m and maze[r][c] != 1:
r += dir[0]
c += dir[1]

r -= dir[0]
c -= dir[1]

if r == destination[0] and c == destination[1]:
return True
if maze[r][c] != -1:
maze[r][c] = -1
q.append([r, c])
return False

if __name__ =="__main__":
maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]]
start = [0,4]
destination = [4,4]

sol = Solution()
result = sol.hasPath(maze, start, destination)
print("Result: ", result)