Skip to content

Commit ab39dbc

Browse files
authored
Merge pull request neetcode-gh#391 from adityadmahale/main
Create 261-Graph-Valid-Tree.java and 252-Meeting-Rooms.java
2 parents 901ae92 + 9c61f7c commit ab39dbc

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

java/252-Meeting-Rooms.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition of Interval:
3+
* public class Interval {
4+
* int start, end;
5+
* Interval(int start, int end) {
6+
* this.start = start;
7+
* this.end = end;
8+
* }
9+
* }
10+
*/
11+
12+
public class Solution {
13+
/**
14+
* @param intervals: an array of meeting time intervals
15+
* @return: if a person could attend all meetings
16+
*/
17+
public boolean canAttendMeetings(List<Interval> intervals) {
18+
int length = intervals.size();
19+
if (intervals.size() == 0 || length == 1) return true;
20+
// Write your code here
21+
22+
int[] start = new int[length];
23+
int[] end = new int[length];
24+
for (int i = 0; i < length; i++) {
25+
start[i] = intervals.get(i).start;
26+
end[i] = intervals.get(i).end;
27+
}
28+
29+
Arrays.sort(start);
30+
Arrays.sort(end);
31+
32+
int j = 0;
33+
while (j + 1 < length) {
34+
if (end[j] > start[j + 1]) return false;
35+
j++;
36+
}
37+
38+
return true;
39+
}
40+
}

java/261-Graph-Valid-Tree.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class Solution {
2+
3+
private Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
4+
5+
public boolean validTree(int n, int[][] edges) {
6+
if (n == 0 || n == 1) return true;
7+
8+
if (edges.length == 0) return false;
9+
10+
for (var edge: edges) {
11+
var node1 = edge[0];
12+
var node2 = edge[1];
13+
adjacencyList.putIfAbsent(node1, new ArrayList<>());
14+
adjacencyList.putIfAbsent(node2, new ArrayList<>());
15+
adjacencyList.get(node1).add(node2);
16+
adjacencyList.get(node2).add(node1);
17+
}
18+
19+
Set<Integer> visited = new HashSet<>();
20+
21+
return depthFirstSearch(0, -1, visited) && visited.size() == n;
22+
}
23+
24+
private boolean depthFirstSearch(int node, int previous, Set<Integer> visited) {
25+
if (visited.contains(node))
26+
return false;
27+
28+
visited.add(node);
29+
30+
for (var neighbor: adjacencyList.get(node)) {
31+
if (neighbor == previous)
32+
continue;
33+
34+
if (!depthFirstSearch(neighbor, node, visited))
35+
return false;
36+
}
37+
38+
return true;
39+
}
40+
}

0 commit comments

Comments
 (0)