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
20 changes: 20 additions & 0 deletions findCeleb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:


class Solution:
def findCelebrity(self, n: int) -> int:
# T: O(n), S: O(1)
# First pass: find the candidate
candidate = 0
for i in range(1, n):
if knows(candidate, i):
candidate = i

# Second pass: verify the candidate
for i in range(n):
if i != candidate:
if knows(candidate, i) or not knows(i, candidate):
return -1
return candidate
34 changes: 34 additions & 0 deletions optimizeWater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
def minCostToSupplyWater(
self, n: int, wells: List[int], pipes: List[List[int]]
) -> int:
# T: O(E log E), S: O(1)
# Initialize parent pointers for Union-Find
parent = [i for i in range(n + 1)]

def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # Path compression
x = parent[x]
return x

def union(x, y):
root_x, root_y = find(x), find(y)
if root_x == root_y:
return False
parent[root_x] = root_y
return True

# Add virtual edges from node 0 to each house with well cost
edges = [[0, i + 1, cost] for i, cost in enumerate(wells)]
# Add existing pipes
edges += pipes
# Sort all edges by cost
edges.sort(key=lambda x: x[2])

total_cost = 0
for u, v, cost in edges:
if union(u, v):
total_cost += cost

return total_cost