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
22 changes: 22 additions & 0 deletions celebrity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# findCelebrity:
# - Check each person to see if they could be a celebrity.
# - A celebrity knows no one and is known by everyone else.
# - Use nested loops to verify the conditions for each person.

# TC: O(n^2) due to nested checks with knows(i, j).
# SC: O(n) for storing possible celebrities.


class Solution:
def findCelebrity(self, n: int) -> int:

isCelebrity = [True] * n
for i in range(n):
if isCelebrity[i]:
for j in range(n):
if j != i and (knows(i, j) or not knows(j, i)):
isCelebrity[i] = False
break
if isCelebrity[i]:
return i
return -1
43 changes: 43 additions & 0 deletions optimize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# minCostToSupplyWater:
# - Treat wells as edges from a virtual node 0 to each house.
# - Use Kruskal’s algorithm with Union-Find to build a minimum spanning tree.
# - Sort all edges (wells + pipes) and greedily connect components.

# TC: O(E log E), E = n + len(pipes) (for sorting edges).
# SC: O(n) for Union-Find structure.


class Solution:
def minCostToSupplyWater(self, n: int, wells: List[int], pipes: List[List[int]]) -> int:
n += 1
parents = [-1] * n

def find(a):
if parents[a] == -1:
return a
else:
parents[a] = find(parents[a])
return parents[a]

def union(a, b, cost):
parentA = find(a)
parentB = find(b)

if parentA != parentB:
parents[parentB] = parentA
return cost

return 0

edgesList = [(wells[i - 1], 0, i) for i in range(1, n)]

for cityOne, cityTwo, cost in pipes:
edgesList.append((cost, cityOne, cityTwo))

edgesList.sort()

totalCost = 0
for cost, cityOne, cityTwo in edgesList:
totalCost += union(cityOne, cityTwo, cost)

return totalCost