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
27 changes: 27 additions & 0 deletions Find the Town Judge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
'''
Solution : In-Degrees array
For a relationship a-->Trusts-->b
- +1 for b
- -1 for a
At the end, if in_degrees of a person == n-1, we found the judge
Time Complexity: O(N)
Space Complexity: O(N)
'''
class Solution:
def findJudge(self, n: int, trust: List[List[int]]) -> int:
in_degrees = [0]*n

for relationship in trust:
a = relationship[0]
b = relationship[1]

# a trusts b (people are 1->n indexed)
in_degrees[b-1]+=1 # increse count of people trusting b
in_degrees[a-1]-=1 # decrease count of 'a' as it's trusting someone

for person_label in range(len(in_degrees)):
if in_degrees[person_label]==n-1: # n-1 people trusting and this person not trusting anyone else
return person_label+1 # Found judge.

return -1 # No Judge

79 changes: 79 additions & 0 deletions The Maze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
'''
Solution: BFS
Time complexity: O(m*n)
Space Complexity: O(m*n)
'''
class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
rows = len(maze)
cols = len(maze[0])

bfs_queue = deque()

bfs_queue.append(start)
maze[start[0]][start[1]] = 2 # mark visited

while bfs_queue:
parent_row, parent_col = bfs_queue.popleft()

# Try rolling ball to right:
row = parent_row
col = parent_col

while col<cols and maze[row][col]!=1:
col+=1
col=col-1 # where ball stopped

if [row,col]==destination: # ball stoped at target
return True

if maze[row][col]!=2:
bfs_queue.append([row,col])
maze[row][col]=2

# Try rolling ball down:
row = parent_row
col = parent_col

while row<rows and maze[row][col]!=1:
row+=1
row=row-1 # where ball stopped

if [row,col]==destination: # ball stoped at target
return True

if maze[row][col]!=2:
bfs_queue.append([row,col])
maze[row][col]=2

# Try rolling ball to left:
row = parent_row
col = parent_col

while col>=0 and maze[row][col]!=1:
col-=1
col=col+1 # where ball stopped

if [row,col]==destination: # ball stoped at target
return True

if maze[row][col]!=2:
bfs_queue.append([row,col])
maze[row][col]=2

# Try rolling ball upwards:
row = parent_row
col = parent_col

while row>=0 and maze[row][col]!=1:
row-=1
row=row+1 # where ball stopped

if [row,col]==destination: # ball stoped at target
return True

if maze[row][col]!=2:
bfs_queue.append([row,col])
maze[row][col]=2

return False