Skip to content

Commit

Permalink
Added codes for 23 April
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanmay-312 committed Apr 23, 2024
1 parent 72b0660 commit b4e33c8
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 0 deletions.
46 changes: 46 additions & 0 deletions GeeksForGeeks/April/23-4-24/GFG.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.util.*;

class GFG {
public static void main(String args[]) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
int n = Integer.parseInt(read.readLine());
Solution ob = new Solution();
System.out.println(ob.firstElement(n));
}
}
}
// } Driver Code Ends


// User function Template for Java
class Solution
{
static int firstElement(int n)
{
// code here
int mod = 1000000007;

if(n <= 2)
{
return 1;
}

int first = 1;
int second = 1;
int res = 0;

for(int i = 0 ; i < n -2; i++)
{
res = (first + second) % mod;
first = second;
second = res;
}

return res % mod;
}
}
2 changes: 2 additions & 0 deletions GeeksForGeeks/April/23-4-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n)
Space complexity - O(1)
2 changes: 2 additions & 0 deletions LeetCode/April/23-4-24/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time complexity - O(n)
Space complexity - O(n)
50 changes: 50 additions & 0 deletions LeetCode/April/23-4-24/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class Solution
{
public List<Integer> findMinHeightTrees(int n, int[][] edges)
{
if (n == 0 || edges.length == 0)
return new ArrayList<>(Arrays.asList(0));

List<Integer> ans = new ArrayList<>();
Map<Integer, Set<Integer>> graph = new HashMap<>();

for (int i = 0; i < n; ++i)
graph.put(i, new HashSet<>());

for (int[] edge : edges)
{
int u = edge[0];
int v = edge[1];
graph.get(u).add(v);
graph.get(v).add(u);
}

for (Map.Entry<Integer, Set<Integer>> entry : graph.entrySet())
{
int label = entry.getKey();
Set<Integer> children = entry.getValue();

if (children.size() == 1)
ans.add(label);
}

while (n > 2)
{
n -= ans.size();
List<Integer> nextLeaves = new ArrayList<>();

for (int leaf : ans)
{
int u = (int) graph.get(leaf).iterator().next();
graph.get(u).remove(leaf);

if (graph.get(u).size() == 1)
nextLeaves.add(u);
}

ans = nextLeaves;
}

return ans;
}
}

0 comments on commit b4e33c8

Please sign in to comment.