Skip to content

Commit

Permalink
heap done
Browse files Browse the repository at this point in the history
  • Loading branch information
mitibirru committed Jul 10, 2024
1 parent 9b184c0 commit 4e6e69e
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 0 deletions.
60 changes: 60 additions & 0 deletions heap/KLargestElementStream.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package heap;

import java.util.PriorityQueue;
import java.util.Scanner;

public class KLargestElementStream {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

int n = sc.nextInt();

if (n <= 0) {
System.out.println("The size of array should be greater than 0.");
sc.close();
return;
}

int k = sc.nextInt();
if (k < 1 || k > n) {
System.out.println("The value of k should be in range of 1 and " + n + '.');
sc.close();
return;
}

int[] arr = new int[n];

for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

System.out.println(kthLargest(arr, n, k));

sc.close();
}

static int[] kthLargest(int[] arr, int n, int k) {
int[] res = new int[n];

PriorityQueue<Integer> pq = new PriorityQueue<>();

for (int i = 0; i < n; i++) {
if (pq.size() < k) {
pq.offer(arr[i]);
} else {
if (arr[i] > pq.peek()) {
pq.poll();
pq.offer(arr[i]);
}
}

if (pq.size() >= k) {
res[i] = pq.peek();
} else {
res[i] = -1;
}
}

return res;
}
}
60 changes: 60 additions & 0 deletions heap/RearrangeCharacters.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package heap;

import java.util.PriorityQueue;
import java.util.Scanner;

public class RearrangeCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

System.out.println(rearrangeCharacters(str));

sc.close();
}

static String rearrangeCharacters(String s) {
int[] map = new int[26];
for (char ch : s.toCharArray()) {
map[ch - 'a']++;
}

StringBuilder ans = new StringBuilder();
PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> b.freq - a.freq);

for (int i = 0; i < 26; i++) {
if (map[i] > 0) {
pq.offer(new Pair((char) ('a' + i), map[i]));
}
}

Pair hold = pq.poll();
ans.append(hold.ch);
hold.freq--;

while (!pq.isEmpty()) {
Pair curr = pq.poll();
ans.append(curr.ch);
curr.freq--;

if (hold.freq > 0) {
pq.offer(hold);
}

hold = curr;
}

return ans.length() == s.length() ? ans.toString() : "";
}
}

class Pair {
char ch;
int freq;

public Pair(char ch, int freq) {
this.ch = ch;
this.freq = freq;
}
}

0 comments on commit 4e6e69e

Please sign in to comment.