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 FindCelebrity.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//TC-O(n^2) SC-O(N)
public class FindCelebrity {
private int numberOfPeople;
public int findCelebrity(int n) {
numberOfPeople = n;
int celebrityCandidate = 0;
for (int i = 0; i < n; i++) {
if (knows(celebrityCandidate, i)) {
celebrityCandidate = i;
}
}
if (isCelebrity(celebrityCandidate)) {
return celebrityCandidate;
}
return -1;
}

private boolean isCelebrity(int i) {
for (int j = 0; j < numberOfPeople; j++) {
if (i == j) continue;
if (knows(i, j) || !knows(j, i)) {
return false;
}
}
return true;
}
}
48 changes: 48 additions & 0 deletions OptimizeWaterDistributionInVillage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the Time and Space complexity for this approach?

public class OptimizeWaterDistributionInVillage {
int[] parent;
public int minCostToSupplyWater(int n, int[] wells, int[][] pipes) {
List<int[]> edges=new ArrayList<>();
parent=new int[n+1];
for(int i=0;i<wells.length;i++){
edges.add(new int[]{0,i+1,wells[i]});
parent[i+1] =i+1;
System.out.println(parent[i+1]+"--");
}
for(int i=0;i<pipes.length;i++){
edges.add(new int[]{pipes[i][0],pipes[i][1],pipes[i][2]});
}

Collections.sort(edges,(a, b)-> a[2]-b[2]);

//kruskal's algorithm starts

int cost = 0;

for(int[] edge : edges){
System.out.println(edge[0]+"--"+edge[1]+"--"+edge[2]);
int x = Union(edge[0]);
int y = Union(edge[1]);

if(x != y){
cost += edge[2];
parent[y] = x;
}
}
return cost;
}


private int Union(int val){

if(val != parent[val]){
parent[val] = Union(parent[val]);
}

return parent[val];

}
}