diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 0000000..e4c1dfe --- /dev/null +++ b/Problem1.py @@ -0,0 +1,30 @@ +## Problem1 Find Judge (https://leetcode.com/problems/find-the-town-judge/) +# Time Complexity: O(N + E) +# - We iterate through the trust array of size E once to compute net degrees: O(E). +# - We iterate through the range from 1 to N to find the town judge: O(N). +# - Overall Time Complexity: O(N + E), where N is the number of people and E is the number of trust relationships. +# +# Space Complexity: O(N) +# - We create an array 'indegrees' of size (N + 1) to track the net trust score for each person: O(N). + +class Solution: + def findJudge(self, n: int, trust: List[List[int]]) -> int: + # Array to track net trust count (In-degree minus Out-degree) for people 1 through n + indegrees = [0] * (n + 1) + + # For every trust relationship [a, b]: + # 'a' trusts 'b', so 'a' loses 1 point (trusts someone, violating judge property 2) + # 'b' gains 1 point (is trusted by someone, building towards judge property 1) + for trustee, trusted in trust: + indegrees[trustee] -= 1 + indegrees[trusted] += 1 + + # Check each person from 1 to n + # The judge trusts nobody (-0 out-degree) and is trusted by everyone else (+(n - 1) in-degree), + # yielding a net score of exactly n - 1. + for i in range(1, n + 1): + if indegrees[i] == n - 1: + return i + + # If no person satisfies the judge condition, return -1 + return -1 \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 0000000..e522171 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,33 @@ +## Problem2 The Maze (https://leetcode.com/problems/the-maze/) +def has_path(maze: list[list[int]], start: list[int], destination: list[int]) -> bool: + rows, cols = len(maze), len(maze[0]) + directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] + + def dfs(r: int, c: int) -> bool: + # If this stopping position was already visited, skip it + if maze[r][c] == 2: + return False + + # Check if we reached the destination stopping point + if r == destination[0] and c == destination[1]: + return True + + # Mark current stopping position as visited + maze[r][c] = 2 + + # Try rolling in all 4 directions + for dr, dc in directions: + nr, nc = r, c + + # Keep rolling until hitting a wall (1) or boundary + while 0 <= nr + dr < rows and 0 <= nc + dc < cols and maze[nr + dr][nc + dc] != 1: + nr += dr + nc += dc + + # Recursively explore from the stopped position + if dfs(nr, nc): + return True + + return False + + return dfs(start[0], start[1]) \ No newline at end of file