Skip to content

Commit 2f0343e

Browse files
Heap DataStructure
1 parent 9484c7e commit 2f0343e

File tree

8 files changed

+384
-0
lines changed

8 files changed

+384
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import java.util.*;
2+
3+
class Twitter {
4+
private static int timeStamp = 0;
5+
private static class Tweet {
6+
int id;
7+
int time;
8+
Tweet next;
9+
10+
public Tweet(int id, int time) {
11+
this.id = id;
12+
this.time = time;
13+
}
14+
}
15+
16+
17+
private Map<Integer, Set<Integer>> followMap;
18+
19+
private Map<Integer, Tweet> tweetMap;
20+
21+
public Twitter() {
22+
followMap = new HashMap<>();
23+
tweetMap = new HashMap<>();
24+
}
25+
26+
/** User posts a new tweet */
27+
public void postTweet(int userId, int tweetId) {
28+
Tweet newTweet = new Tweet(tweetId, timeStamp++);
29+
if (tweetMap.containsKey(userId)) {
30+
newTweet.next = tweetMap.get(userId);
31+
}
32+
tweetMap.put(userId, newTweet);
33+
}
34+
35+
/** Retrieve the 10 most recent tweet ids in the user's news feed */
36+
public List<Integer> getNewsFeed(int userId) {
37+
List<Integer> result = new ArrayList<>();
38+
// Min-heap to get most recent tweets first
39+
PriorityQueue<Tweet> pq = new PriorityQueue<>((a, b) -> b.time - a.time);
40+
41+
// Add own tweets
42+
if (tweetMap.containsKey(userId)) {
43+
pq.offer(tweetMap.get(userId));
44+
}
45+
46+
// Add followees' tweets
47+
if (followMap.containsKey(userId)) {
48+
for (int followee : followMap.get(userId)) {
49+
if (tweetMap.containsKey(followee)) {
50+
pq.offer(tweetMap.get(followee));
51+
}
52+
}
53+
}
54+
55+
// Retrieve top 10 tweets
56+
while (!pq.isEmpty() && result.size() < 10) {
57+
Tweet t = pq.poll();
58+
result.add(t.id);
59+
if (t.next != null) pq.offer(t.next);
60+
}
61+
return result;
62+
}
63+
64+
65+
public void follow(int followerId, int followeeId) {
66+
if (followerId == followeeId) return; // can’t follow self
67+
followMap.putIfAbsent(followerId, new HashSet<>());
68+
followMap.get(followerId).add(followeeId);
69+
}
70+
71+
/** Follower unfollows a followee */
72+
public void unfollow(int followerId, int followeeId) {
73+
if (!followMap.containsKey(followerId)) return;
74+
followMap.get(followerId).remove(followeeId);
75+
}
76+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import java.util.*;
2+
3+
public class MedianFinder {
4+
private PriorityQueue<Integer> maxHeap; // left half (small)
5+
private PriorityQueue<Integer> minHeap; // right half (larger)
6+
7+
public MedianFinder() {
8+
// Max-heap stores the smaller half
9+
maxHeap = new PriorityQueue<>(Collections.reverseOrder());
10+
// Min-heap stores the larger half
11+
minHeap = new PriorityQueue<>();
12+
}
13+
14+
15+
public void addNum(int num) {
16+
// Step 1: Add to maxHeap
17+
maxHeap.offer(num);
18+
19+
// Step 2: Balance heaps (ensure all in maxHeap <= all in minHeap)
20+
minHeap.offer(maxHeap.poll());
21+
22+
// Step 3: Maintain size property (maxHeap can be larger by 1)
23+
if (maxHeap.size() < minHeap.size()) {
24+
maxHeap.offer(minHeap.poll());
25+
}
26+
}
27+
28+
public double findMedian() {
29+
if (maxHeap.size() == minHeap.size()) {
30+
// Even number of elements → average of two middles
31+
return (maxHeap.peek() + minHeap.peek()) / 2.0;
32+
} else {
33+
// Odd → top of maxHeap
34+
return maxHeap.peek();
35+
}
36+
}
37+
38+
39+
public static void main(String[] args) {
40+
MedianFinder mf = new MedianFinder();
41+
42+
mf.addNum(1);
43+
System.out.println("After adding 1, Median = " + mf.findMedian());
44+
45+
mf.addNum(2);
46+
System.out.println("After adding 2, Median = " + mf.findMedian());
47+
48+
mf.addNum(3);
49+
System.out.println("After adding 3, Median = " + mf.findMedian());
50+
51+
mf.addNum(4);
52+
System.out.println("After adding 4, Median = " + mf.findMedian());
53+
54+
mf.addNum(5);
55+
System.out.println("After adding 5, Median = " + mf.findMedian());
56+
}
57+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.*;
2+
3+
public class HandOfStraights {
4+
5+
public static boolean isNStraightHand(int[] hand, int groupSize) {
6+
// Base check
7+
if (hand.length % groupSize != 0) return false;
8+
9+
// Step 1: Count frequency of each card
10+
TreeMap<Integer, Integer> cardCount = new TreeMap<>();
11+
for (int card : hand) {
12+
cardCount.put(card, cardCount.getOrDefault(card, 0) + 1);
13+
}
14+
15+
// Step 2: Iterate over cards in sorted order
16+
for (int card : cardCount.keySet()) {
17+
int freq = cardCount.get(card);
18+
if (freq > 0) { // If we still have cards to group
19+
20+
for (int next = card; next < card + groupSize; next++) {
21+
if (cardCount.getOrDefault(next, 0) < freq) {
22+
return false;
23+
}
24+
cardCount.put(next, cardCount.get(next) - freq);
25+
}
26+
}
27+
}
28+
29+
return true;
30+
}
31+
32+
33+
public static void main(String[] args) {
34+
int[] hand1 = {1,2,3,6,2,3,4,7,8};
35+
int groupSize1 = 3;
36+
System.out.println("Output 1: " + isNStraightHand(hand1, groupSize1)); // true
37+
38+
int[] hand2 = {1,2,3,4,5};
39+
int groupSize2 = 4;
40+
System.out.println("Output 2: " + isNStraightHand(hand2, groupSize2)); // false
41+
}
42+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.*;
2+
3+
public class IPO {
4+
public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
5+
int n = profits.length;
6+
int[][] projects = new int[n][2];
7+
8+
// Combine capital and profit for each project
9+
for (int i = 0; i < n; i++) {
10+
projects[i][0] = capital[i];
11+
projects[i][1] = profits[i];
12+
}
13+
14+
// Sort projects by required capital (ascending)
15+
Arrays.sort(projects, Comparator.comparingInt(a -> a[0]));
16+
17+
18+
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
19+
20+
int i = 0;
21+
for (int t = 0; t < k; t++) {
22+
// Add all affordable projects to the heap
23+
while (i < n && projects[i][0] <= w) {
24+
maxHeap.offer(projects[i][1]);
25+
i++;
26+
}
27+
28+
// If no project is affordable, break early
29+
if (maxHeap.isEmpty()) break;
30+
31+
32+
w += maxHeap.poll(); // Pick the most profitable project
33+
}
34+
35+
return w;
36+
}
37+
38+
public static void main(String[] args) {
39+
IPO obj = new IPO();
40+
int k = 2, w = 0;
41+
int[] profits = {1, 2, 3};
42+
int[] capital = {0, 1, 1};
43+
44+
System.out.println(obj.findMaximizedCapital(k, w, profits, capital)); // Output: 4
45+
}
46+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.*;
2+
3+
class MergeMSortedArrays {
4+
static class Element {
5+
int value;
6+
int arrayIndex;
7+
int elementIndex;
8+
9+
Element(int value, int arrayIndex, int elementIndex) {
10+
this.value = value;
11+
this.arrayIndex = arrayIndex;
12+
this.elementIndex = elementIndex;
13+
}
14+
}
15+
16+
public static List<Integer> mergeSortedArrays(int[][] arrays) {
17+
PriorityQueue<Element> minHeap = new PriorityQueue<>(Comparator.comparingInt(e -> e.value));
18+
List<Integer> result = new ArrayList<>();
19+
20+
// Step 1: Push the first element of each array
21+
for (int i = 0; i < arrays.length; i++) {
22+
if (arrays[i].length > 0) {
23+
minHeap.offer(new Element(arrays[i][0], i, 0));
24+
}
25+
}
26+
27+
// Step 2: Extract the smallest element and push the next from same array
28+
while (!minHeap.isEmpty()) {
29+
Element current = minHeap.poll();
30+
result.add(current.value);
31+
32+
int nextIndex = current.elementIndex + 1;
33+
if (nextIndex < arrays[current.arrayIndex].length) {
34+
minHeap.offer(new Element(
35+
arrays[current.arrayIndex][nextIndex],
36+
current.arrayIndex,
37+
nextIndex
38+
));
39+
}
40+
}
41+
42+
return result;
43+
}
44+
45+
public static void main(String[] args) {
46+
int[][] arrays = {
47+
{1, 4, 7},
48+
{2, 5, 8},
49+
{3, 6, 9}
50+
};
51+
52+
System.out.println("Merged Sorted Array: " + mergeSortedArrays(arrays));
53+
}
54+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.*;
2+
3+
public class SlidingWindowMaximum {
4+
public static int[] maxSlidingWindow(int[] nums, int k) {
5+
int n = nums.length;
6+
int[] result = new int[n - k + 1];
7+
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]); // Max heap based on value
8+
9+
for (int i = 0; i < n; i++) {
10+
//add current
11+
maxHeap.offer(new int[]{nums[i], i});
12+
13+
// remove elements outside the current window
14+
while (maxHeap.peek()[1] <= i - k) {
15+
maxHeap.poll();
16+
}
17+
18+
// Store the max for the current window
19+
if (i >= k - 1) {
20+
result[i - k + 1] = maxHeap.peek()[0];
21+
}
22+
}
23+
24+
return result;
25+
}
26+
27+
public static void main(String[] args) {
28+
int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
29+
int k = 3;
30+
System.out.println(Arrays.toString(maxSlidingWindow(nums, k)));
31+
}
32+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.*;
2+
3+
public class TaskScheduler {
4+
5+
public static int leastInterval(char[] tasks, int n) {
6+
int[] freq = new int[26];
7+
for (char c : tasks) {
8+
freq[c - 'A']++;
9+
}
10+
11+
Arrays.sort(freq);
12+
int maxFreq = freq[25];
13+
int idleSlots = (maxFreq - 1) * n;
14+
15+
// Fill idle slots with remaining tasks
16+
for (int i = 24; i >= 0 && idleSlots > 0; i--) {
17+
idleSlots -= Math.min(freq[i], maxFreq - 1);
18+
}
19+
20+
idleSlots = Math.max(0, idleSlots);
21+
22+
return tasks.length + idleSlots;
23+
}
24+
25+
public static void main(String[] args) {
26+
char[] tasks1 = {'A','A','A','B','B','B'};
27+
int n1 = 2;
28+
System.out.println("Output 1: " + leastInterval(tasks1, n1)); // 8
29+
30+
char[] tasks2 = {'A','C','A','B','D','B'};
31+
int n2 = 1;
32+
System.out.println("Output 2: " + leastInterval(tasks2, n2)); // 6
33+
34+
char[] tasks3 = {'A','A','A','B','B','B'};
35+
int n3 = 0;
36+
System.out.println("Output 3: " + leastInterval(tasks3, n3)); // 6
37+
}
38+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.util.*;
2+
3+
public class TopKFrequentElements {
4+
5+
public static int[] topKFrequent(int[] nums, int k) {
6+
// Step 1: Count frequencies
7+
Map<Integer, Integer> freqMap = new HashMap<>();
8+
for (int num : nums) {
9+
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
10+
}
11+
12+
// Step 2: Use a min-heap to keep top k elements
13+
PriorityQueue<Map.Entry<Integer, Integer>> minHeap =
14+
new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());
15+
16+
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
17+
minHeap.offer(entry);
18+
if (minHeap.size() > k) {
19+
minHeap.poll(); // remove least frequent element
20+
}
21+
}
22+
23+
// Step 3: Extract elements from heap
24+
int[] result = new int[k];
25+
for (int i = k - 1; i >= 0; i--) {
26+
result[i] = minHeap.poll().getKey();
27+
}
28+
29+
return result;
30+
}
31+
32+
public static void main(String[] args) {
33+
int[] nums = {1, 1, 1, 2, 2, 3, 3, 3, 3, 4};
34+
int k = 2;
35+
36+
int[] res = topKFrequent(nums, k);
37+
System.out.println("Top " + k + " frequent elements: " + Arrays.toString(res));
38+
}
39+
}

0 commit comments

Comments
 (0)