VOOZH about

URL: https://www.geeksforgeeks.org/dsa/k-th-smallest-element-removing-integers-natural-numbers/

⇱ K-th smallest element after removing some integers from natural numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K-th smallest element after removing some integers from natural numbers

Last Updated : 23 Jul, 2025

Given an array arr[] of size 'n' and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[n-1] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print "-1".

Examples :

Input: arr[] = [ 1 ] and k = 1.
Output: 2
Explanation: Natural numbers are {1, 2, 3, 4, .... }. After removing {1}, we get {2, 3, 4, ...}. Now, 2-th smallest element = 2.

Input: arr[] = [ 1, 3 ], k = 4.
Output: 6
Explanation: First 5 Natural number {1, 2, 3, 4, 5, 6, .. }. After removing {1, 3}, we get {2, 4, 5, 6, ... }.Now, 4-th smallest element = 6.''

In this article we have discussed the Naive approach in detail, this problem can be solved in more efficient ways. You can find them here K-th smallest element after removing given integers from natural numbers | Set 2

[Naive Approach] Using Nested Loop – O(n * k) Time and O(1) Space

  • Iterate Over Natural Numbers: We start from 1 and check each number to see if it’s in the arr[] (i.e., removed).
  • Check if Number is to be Removed: For each natural number, we use a nested loop to check if it exists in the removed numbers list (arr[]).
  • Count Valid Numbers: If the number is not found in the removed list, it’s counted as a valid number.
  • Return the k-th Valid Number: When we’ve counted k valid numbers, return the current number.

Output
2

[Expected Approach for Large k] Using Sort – O(n log n) Time and O(1) Space

The key idea is that every time we remove a number less than or equal to the current value of k, the position of k moves forward. So, by the time we finish checking all the numbers in the array, k will represent the correct k-th smallest number in the remaining sequence. Please refer K-th smallest element after removing given integers from natural numbers | Set 2 for implementation

[Expected Approach for Large n] Using Set– O(n + k) Time and O(n) Space

We insert all items in a hash set and consider only those items that are not in the set. Please refer K-th smallest element after removing given integers from natural numbers | Set 2 for implementation

In this article we have discussed the Naive approach in detail, this problem can be solved in more efficient ways. You can find them here

Comment
Article Tags:
Article Tags: