Skip to content

Commit 14a7107

Browse files
seungyeonchoiseungyeonchoiclaude
authored
[seungyeonchoi] WEEK 01 Solutions (#2916)
* contains duplicate solution Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * top k frequent elements solution Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * top k frequent elements bucket sort solution Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: seungyeonchoi <sychoi.dev@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6431da0 commit 14a7107

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public boolean containsDuplicate(int[] nums) {
3+
Set<Integer> duplicates = new HashSet<>();
4+
for (int i=0; i<nums.length;i++) {
5+
// duplicates.add(nums[i]);
6+
// if (duplicates.size() != i+1) {
7+
// return true;
8+
// }
9+
if (!duplicates.add(nums[i])) {
10+
return true;
11+
}
12+
}
13+
return false;
14+
}
15+
16+
/*
17+
complexity
18+
- time: O(n) using a for loop
19+
- space: O(n) declaring a set
20+
*/
21+
22+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class Solution {
2+
public int[] topKFrequent(int[] nums, int k) {
3+
/*
4+
Approach 1
5+
1. using map, key -> num, value -> count
6+
2. sort
7+
*/
8+
9+
Map<Integer, Integer> count = new HashMap<>();
10+
for (int num: nums) { // O(n)
11+
count.put(num, count.getOrDefault(num,0)+1);
12+
}
13+
14+
// return count.entrySet().stream()
15+
// .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
16+
// .map(Map.Entry::getKey)
17+
// .limit(k)
18+
// .mapToInt(Integer::intValue)
19+
// .toArray();
20+
// /*
21+
// Complexity
22+
// - time: O(nlogn) // sort
23+
// - space: O(n) // declare map?
24+
// */
25+
26+
27+
/*
28+
Approach 2
29+
1. using map, key -> num, value -> count
30+
2. Initialize a 2D dynamic array (buckets) and group numbers by their frequency
31+
*/
32+
List<List<Integer>> buckets = new ArrayList<>();
33+
for (int i = 0; i <= nums.length; i++) {
34+
buckets.add(new ArrayList<>());
35+
}
36+
for (int key: count.keySet()) {
37+
buckets.get(count.get(key)).add(key);
38+
}
39+
40+
int[] result = new int[k];
41+
int idx = 0;
42+
for (int i = buckets.size()-1;i>=0;i--) {
43+
for (int j = 0; j < buckets.get(i).size(); j++) {
44+
if (idx<k) {
45+
result[idx] = buckets.get(i).get(j);
46+
idx++;
47+
} else {
48+
return result;
49+
}
50+
51+
}
52+
}
53+
54+
return result;
55+
/**
56+
Complexity
57+
- time: O(n) -> o(n) + o(n) + o (n+1+ n) -> o(4n+1)
58+
- space: O(n) -> dynamic 2d array (buckets)
59+
*/
60+
}
61+
}

0 commit comments

Comments
 (0)