diff --git a/celebrity.py b/celebrity.py new file mode 100644 index 0000000..3a279ef --- /dev/null +++ b/celebrity.py @@ -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 \ No newline at end of file diff --git a/optimize.py b/optimize.py new file mode 100644 index 0000000..2274da5 --- /dev/null +++ b/optimize.py @@ -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 \ No newline at end of file