How to use Sets In Javascript
In this approach, Initialize an empty set to store the integers in the array. Start a loop from 1 (the smallest natural number). Check if the current number exists in the set. If it doesn’t, increment the count of found smallest elements. Inside the loop, if the count of found smallest elements equals k, return the current number.
Example: The example below shows how to find K-th smallest element after removing some integers from natural numbers using Sets.
function kthSmallestAfterRemoval(array, k) {
// Create a Set to store integers in the array
const set = new Set(array);
// Count smallest elements
let count = 0;
for (let i = 1; ; i++) {
// increment the count
if (!set.has(i)) {
count++;
// Return the k-th smallest number
if (count === k) return i;
}
}
}
const array = [3, 5];
const k = 2;
console.log(kthSmallestAfterRemoval(array, k));
Output
2
Time Complexity: O(n + k).
Space Complexity: O(n)
K-th Smallest Element after Removing some Integers from Natural Numbers using JavaScript
Given an array of size “n” and a positive integer k our task is to find the K-th smallest element that remains after removing certain integers from the set of natural numbers using JavaScript.
Example:
Input: array = [3, 5]
k = 2
Output: 2
Explanation: The natural numbers are [1, 2, 3, 4, 5......] and after removing elements 3 and 5 from the natural numbers, the remaining numbers are [1, 2, 4....].
The 2nd smallest number from the remaining numbers is 2.
Below are the approaches to finding the K-th smallest element after removing some integers from natural numbers using JavaScript:
Table of Content
- Brute Force approach
- Using Quick Select
- Flag and Counting Approach
- Using Sets