Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add least-number-of-unique-integers-after-k-removals #325

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Hacktoberfest2022/count-good-nodes-in-binary-tree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
Author: Kabir Singh Mehrok <https://github.com/KabirSinghMehrok>

Title: Count Good Nodes in Binary Tree
Description: Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
*/


public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

class Solution {
public int goodNodes(TreeNode root) {
// dfs traversal to every node
// keep track of the max val along the path
// if given val > maxval, +1 and recurse, with updated maxval
// else, traverse
return recurse(root, root.val);
}

public int recurse(TreeNode root, int maxval)
{
if (root == null) return 0;
if (root.val >= maxval) {
return 1 + recurse(root.right, root.val) + recurse(root.left, root.val);
}
else return recurse(root.right, maxval) + recurse(root.left, maxval);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
Author: Kabir Singh Mehrok <https://github.com/KabirSinghMehrok>

Title: Least Number of Unique Integers after K Removals
Description: Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
*/

class Solution {
public int findLeastNumOfUniqueInts(int[] arr, int k) {
int N = arr.length;
HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
for (int i=0; i<N; i++) h.put(arr[i], h.getOrDefault(arr[i], 0) + 1);

// now make a set of values into arraylist
// sort it in ascending order
// sum values
// stop when >= k

ArrayList<Integer> a = new ArrayList<Integer>(h.values());
Collections.sort(a);

int sum = 0;
int i = 0;
for (i=0; i<a.size(); i++)
{
if (sum >= k) break;
sum += a.get(i);
}

// now there can be two cases
// if sum > k, it implies that we have taken an extra element into account
// if sum == k, it implies we have exact amount of element

if (sum > k) return a.size() - i + 1;
if (sum == k) return a.size() - i;
else return 0;
}
}