Skip to content

Commit

Permalink
Merge pull request #592 from TonyKim9401/main
Browse files Browse the repository at this point in the history
[Tony] WEEK 14 Solutions
  • Loading branch information
TonyKim9401 authored Nov 17, 2024
2 parents f00cbcb + b66b35e commit 187e613
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 0 deletions.
26 changes: 26 additions & 0 deletions binary-tree-level-order-traversal/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// TC: O(n)
// need to visit all nodes
// SC: O(n)
// normally O(log n) required however, O(n) in the worst case
class Solution {
private List<List<Integer>> output = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
dfs(0, root);
return output;
}

private void dfs(int level, TreeNode node) {
if (node == null) return;

if (output.size() == level) {
List<Integer> inside = new ArrayList<>();
inside.add(node.val);
output.add(inside);
} else {
output.get(level).add(node.val);
}
level += 1;
dfs(level, node.left);
dfs(level, node.right);
}
}
32 changes: 32 additions & 0 deletions house-robber-ii/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// TC: O(n)
// visit all nums at least once
// SC: O(1)
// only constant memory space required
class Solution {
public int rob(int[] nums) {
if (nums.length == 1) return nums[0];

int prev = 0;
int post = 0;
int output1 = 0;

for (int i = 0; i < nums.length - 1; i++) {
int temp = prev;
prev = Math.max(post + nums[i], prev);
post = temp;
}
output1 = prev;

prev = 0;
post = 0;
int output2 = 0;
for (int i = 1; i < nums.length; i++) {
int temp = prev;
prev = Math.max(post + nums[i], prev);
post = temp;
}
output2 = prev;

return Math.max(output1, output2);
}
}
22 changes: 22 additions & 0 deletions meeting-rooms-ii/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// TC: O(n)
// visit all intervals to compare each of start time
// SC: O(n)
// PQ save all intervals in the worst case
public class Solution {
public int minMeetingRooms(List<Interval> intervals) {
if (intervals == null || intervals.isEmpty()) return 0;

intervals.sort((a, b) -> a.start - b.start);

PriorityQueue<Integer> endTimes = new PriorityQueue<>();
endTimes.add(intervals.get(0).end);

for (int i = 1; i < intervals.size(); i++) {
Interval current = intervals.get(i);
if (current.start >= endTimes.peek()) endTimes.poll();
endTimes.add(current.end);
}

return endTimes.size();
}
}
14 changes: 14 additions & 0 deletions reverse-bits/TonyKim9401.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
public class Solution {
public int reverseBits(int n) {
// time complexity O(1)
// space complexity O(1)
int output = 0;

for (int i = 0; i < Integer.SIZE; i++) {
output <<= 1;
output += n & 1;
n >>= 1;
}
return output;
}
}

0 comments on commit 187e613

Please sign in to comment.