The Wayback Machine - https://web.archive.org/web/20240927173838/https://www.geeksforgeeks.org/k-th-smallest-element-removing-integers-natural-numbers/
Open In App

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

Last Updated : 15 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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[p] 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
Natural numbers are {1, 2, 3, 4, .... }
After removing {1}, we get {2, 3, 4, ...}.
Now, K-th smallest element = 2.
Input : arr[] = {1, 3}, k = 4.
Output : 6
First 5 Natural number {1, 2, 3, 4, 5, 6, .. }
After removing {1, 3}, we get {2, 4, 5, 6, ... }.

Method 1 (Simple): 
Make an auxiliary array b[] for presence/absence of natural numbers and initialize all with 0. Make all the integer equal to 1 which are present in array arr[] i.e b[arr[i]] = 1. Now, run a loop and decrement k whenever unmarked cell is encountered. When the value of k is 0, we get the answer.

Steps to solve the problem:

1. declare an array b of size max.

2. mark complete array as unmarked by 0.

3. iterate through i=0 till n:

        * update b[arr[i]] to 1.

4. iterate through j=0 till max:

        * check if b[j] is not equal to 1 then decrement k.

        * check if k is not equal to 0 then return j.

Below is implementation of this approach:  

C++
// C++ program to find the K-th smallest element
// after removing some integers from natural number.
#include <bits/stdc++.h>
#define MAX 1000000
using namespace std;

// Return the K-th smallest element.
int ksmallest(int arr[], int n, int k)
{
    // Making an array, and mark all number as unmarked.
    int b[MAX];
    memset(b, 0, sizeof b);

    // Marking the number present in the given array.
    for (int i = 0; i < n; i++)
        b[arr[i]] = 1;

    for (int j = 1; j < MAX; j++) {
        // If j is unmarked, reduce k by 1.
        if (b[j] != 1)
            k--;

        // If k is 0 return j.
        if (!k)
            return j;
    }
}

// Driven Program
int main()
{
    int k = 1;
    int arr[] = { 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << ksmallest(arr, n, k);
    return 0;
}
Java
// Java program to find the K-th smallest element
// after removing some integers from natural number.
class GFG {

    static final int MAX = 1000000;

    // Return the K-th smallest element.
    static int ksmallest(int arr[], int n, int k)
    {
        // Making an array, and mark
        // all number as unmarked.
        int b[] = new int[MAX];

        // Marking the number present
        // in the given array.
        for (int i = 0; i < n; i++) {
            b[arr[i]] = 1;
        }

        for (int j = 1; j < MAX; j++) {
            // If j is unmarked, reduce k by 1.
            if (b[j] != 1) {
                k--;
            }

            // If k is 0 return j.
            if (k != 1) {
                return j;
            }
        }
        return Integer.MAX_VALUE;
    }

    // Driven code
    public static void main(String[] args)
    {
        int k = 1;
        int arr[] = { 1 };
        int n = arr.length;
        System.out.println(ksmallest(arr, n, k));
    }
}

// This code has been contributed by 29AjayKumar
Python3
# Python program to find the K-th smallest element
# after removing some integers from natural number.
MAX = 1000000


# Return the K-th smallest element.
def ksmallest(arr, n, k):
    
    # Making an array, and mark all number as unmarked.
    b = [0]*MAX;

    # Marking the number present in the given array.
    for i in range(n):
        b[arr[i]] = 1;

    for j in range(1, MAX):
        # If j is unmarked, reduce k by 1.
        if (b[j] != 1):
            k-= 1;

        # If k is 0 return j.
        if (k is not 1):
            return j;
            
# Driven Program
k = 1;
arr = [ 1 ];
n = len(arr);
print(ksmallest(arr, n, k));

# This code contributed by Rajput-Ji
C#
// C# program to find the K-th smallest element
// after removing some integers from natural number.
using System;

class GFG {

    static int MAX = 1000000;

    // Return the K-th smallest element.
    static int ksmallest(int[] arr, int n, int k)
    {
        // Making an array, and mark
        // all number as unmarked.
        int[] b = new int[MAX];

        // Marking the number present
        // in the given array.
        for (int i = 0; i < n; i++) {
            b[arr[i]] = 1;
        }

        for (int j = 1; j < MAX; j++) {
            // If j is unmarked, reduce k by 1.
            if (b[j] != 1) {
                k--;
            }

            // If k is 0 return j.
            if (k != 1) {
                return j;
            }
        }
        return int.MaxValue;
    }

    // Driven code
    public static void Main()
    {
        int k = 1;
        int[] arr = { 1 };
        int n = arr.Length;
        Console.WriteLine(ksmallest(arr, n, k));
    }
}

/* This code contributed by PrinciRaj1992 */
JavaScript
<script>

// Javascript program to find the K-th 
// smallest element after removing some
// integers from natural number.

let MAX = 1000000;

// Return the K-th smallest element.
function ksmallest(arr, n, k)
{
    
    // Making an array, and mark
    // all number as unmarked.
    let b = [];

    // Marking the number present
    // in the given array.
    for(let i = 0; i < n; i++) 
    {
        b[arr[i]] = 1;
    }

    for(let j = 1; j < MAX; j++)
    {
        
        // If j is unmarked, reduce k by 1.
        if (b[j] != 1)
        {
            k--;
        }

        // If k is 0 return j.
        if (k != 1)
        {
            return j;
        }
    }
    return Number.MAX_VALUE;
}
 
// Driver code    
let k = 1;
let arr = [1];
let n = arr.length;

document.write(ksmallest(arr, n, k));
        
// This code is contributed by susmitakundugoaldanga
               
</script>
PHP
<?php
// PHP program to find the K-th smallest element
// after removing some integers from natural number.
$MAX = 10000;

// Return the K-th smallest element.
function ksmallest($arr, $n, $k)
{
    global $MAX;
    
    // Making an array, and mark all number as unmarked.
    $b=array_fill(0, $MAX, 0);

    // Marking the number present in the given array.
    for ($i = 0; $i < $n; $i++)
        $b[$arr[$i]] = 1;

    for ($j = 1; $j < $MAX; $j++) 
    {
        // If j is unmarked, reduce k by 1.
        if ($b[$j] != 1)
            $k--;

        // If k is 0 return j.
        if ($k == 0)
            return $j;
    }
}

// Driver code
    $k = 1;
    $arr = array( 1 );
    $n = count($arr);
    echo ksmallest($arr, $n, $k);

// This code is contributed by mits
?>

Output
2

Time Complexity: O(MAX)
Auxiliary Space: O(MAX)

Method 2 (Efficient): 
First, sort the array arr[]. Observe, there will be arr[0] – 1 numbers between 0 and arr[0], similarly, arr[1] – arr[0] – 1 numbers between arr[0] and arr[1] and so on. So, if k lies between arr[i] – arr[i+1] – 1, then return K-th smallest element in the range. Else reduce k by arr[i] – arr[i+1] – 1 i.e., k = k – (arr[i] – arr[i+1] – 1).

Algorithm to solve the problem: 

1. Sort the array arr[].
2. For i = 1 to n. Find c = arr[i+1] - arr[i] -1.
a) if k - c <= 0, return arr[i-1] + k.
b) else k = k - c.

Below is implementation of this approach: 

C++
// C++ program to find the Kth smallest element
// after removing some integer from first n
// natural number.
#include <bits/stdc++.h>
using namespace std;

// Return the K-th smallest element.
int ksmallest(int arr[], int n, int k)
{
    sort(arr, arr + n);

    // Checking if k lies before 1st element
    if (k < arr[0])
        return k;

    // If k is more than last element
    if (k > arr[n - 1])
        return k + n;

    // Reducing k by numbers before arr[0].
    k -= (arr[0] - 1);

    // Finding k'th smallest element after removing
    // array elements.
    for (int i = 1; i < n; i++) {
        // Finding count of element between i-th
        // and (i-1)-th element.
        int c = arr[i] - arr[i - 1] - 1;
        if (k <= c)
            return arr[i - 1] + k;
        else
            k -= c;
    }

    return arr[n - 1] + k;
}

// Driven Program
int main()
{
    int k = 2;
    int arr[] = { 1, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << ksmallest(arr, n, k);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    // Return the K-th smallest element.
    public static int ksmallest(int[] arr, int k) {
        Arrays.sort(arr);
        int n = arr.length;

        // Checking if k lies before 1st element
        if (k < arr[0])
            return k;

        // If k is more than last element
        if (k > arr[n - 1])
            return k + n;

        // Reducing k by numbers before arr[0].
        k -= (arr[0] - 1);

        // Finding k'th smallest element after removing
        // array elements.
        for (int i = 1; i < n; i++) {
            // Finding count of element between i-th
            // and (i-1)-th element.
            int c = arr[i] - arr[i - 1] - 1;
            if (k <= c)
                return arr[i - 1] + k;
            else
                k -= c;
        }

        return arr[n - 1] + k;
    }

    // Driver Program
    public static void main(String[] args) {
        int k = 2;
        int[] arr = { 1, 3 };
        System.out.println(ksmallest(arr, k));
    }
}
Python3
import numpy as np

# Function to return the K-th smallest element.
def ksmallest(arr, n, k):
    # Sort the array
    arr = np.sort(arr)

    # Checking if k lies before 1st element
    if k < arr[0]:
        return k

    # If k is more than last element
    if k > arr[n - 1]:
        return k + n

    # Reducing k by numbers before arr[0].
    k -= (arr[0] - 1)

    # Finding k'th smallest element after removing array elements.
    for i in range(1, n):
        # Finding count of element between i-th and (i-1)-th element.
        c = arr[i] - arr[i - 1] - 1
        if k <= c:
            return arr[i - 1] + k
        else:
            k -= c

    return arr[n - 1] + k

# Driver Code
if __name__ == "__main__":
    k = 2
    arr = [1, 3]
    n = len(arr)
    print(ksmallest(arr, n, k))
JavaScript
// Function to find the K-th smallest element.
function ksmallest(arr, n, k) {
    arr.sort((a, b) => a - b);

    // Checking if k lies before 1st element
    if (k < arr[0])
        return k;

    // If k is more than last element
    if (k > arr[n - 1])
        return k + n;

    // Reducing k by numbers before arr[0].
    k -= (arr[0] - 1);

    // Finding k'th smallest element after removing
    // array elements.
    for (let i = 1; i < n; i++) {
        // Finding count of element between i-th
        // and (i-1)-th element.
        let c = arr[i] - arr[i - 1] - 1;
        if (k <= c)
            return arr[i - 1] + k;
        else
            k -= c;
    }

    return arr[n - 1] + k;
}

// Driver code
let k = 2;
let arr = [1, 3];
let n = arr.length;
console.log(ksmallest(arr, n, k));

Output
4

Time Complexity: O(nlog(n))
Auxiliary Space: O(1)

Set Approach:

  • Create a set to store the elements of the array.
  • Iterate through the array and add each element to the set.
  • Start changing num to 1, which represents the current generation number.
    If k is greater than 0:
    If the set contains num, continue by incrementing num.
    If num is not available, reduce k by 1 .
    Increase num by1.
  • Returns the value of num as the k-th smallest number.
C++
#include <iostream>
#include <unordered_set>
using namespace std;

int findKthSmallestNumber(int arr[], int n, int k) {
    unordered_set<int> set;
    
    // Add elements from the array to the set
    for (int i = 0; i < n; i++) {
        set.insert(arr[i]);
    }
    
    int num = 1; // Current natural number
    
    while (k > 0) {
        if (set.count(num)) {
            num++;
        } else {
            k--;
            num++;
        }
    }
    
    return num - 1; // Subtract 1 to get the k-th smallest number
}

int main() {
    int arr[] = {1, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
    
    int kthSmallest = findKthSmallestNumber(arr, n, k);
    cout << "K-th smallest number: " << kthSmallest << endl;
    
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.util.HashSet;
import java.util.Set;

public class KthSmallestNumber {
    
    public static void main(String[] args) {
        int[] arr = {1, 3};
        int k = 4;
        int kthSmallest = findKthSmallestNumber(arr, k);
        System.out.println("K-th smallest number: " + kthSmallest);
    }
    
    public static int findKthSmallestNumber(int[] arr, int k) {
        Set<Integer> set = new HashSet<>();
        
        // Add elements from the array to the set
        for (int num : arr) {
            set.add(num);
        }
        
        int num = 1; // Current natural number
        
        while (k > 0) {
            if (set.contains(num)) {
                num++;
            } else {
                k--;
                num++;
            }
        }
        
        return num - 1; // Subtract 1 to get the k-th smallest number
    }
}

//This code is contributed by Sovi
Python3
#Python3 code to demonstrate working of above approach
def find_kth_smallest_number(arr, k):
    unique_nums = set(arr)  # Create a set to store unique elements from the array
    
    num = 1  # Current natural number
    
    while k > 0:
        if num in unique_nums:  # If num is already present in the set
            num += 1
        else:
            k -= 1
            num += 1
    
    return num - 1  # Subtract 1 to get the k-th smallest number

# Driver code
if __name__ == "__main__":
    arr = [1, 3]
    k = 4
    
    kth_smallest = find_kth_smallest_number(arr, k)
    print("K-th smallest number:", kth_smallest)
C#
using System;
using System.Collections.Generic;

class GFG {
    static int FindKthSmallestNumber(int[] arr, int n,
                                     int k)
    {
        HashSet<int> set = new HashSet<int>();

        // Add elements from the array to the set
        for (int i = 0; i < n; i++) {
            set.Add(arr[i]);
        }

        int num = 1; // Current natural number

        while (k > 0) {
            if (set.Contains(num)) {
                num++;
            }
            else {
                k--;
                num++;
            }
        }

        return num - 1; // Subtract 1 to get the k-th
                        // smallest number
    }

    static void Main()
    {
        int[] arr = { 1, 3 };
        int n = arr.Length;
        int k = 4;

        int kthSmallest = FindKthSmallestNumber(arr, n, k);
        Console.WriteLine("K-th smallest number: "
                          + kthSmallest);
    }
}
JavaScript
function findKthSmallestNumber(arr, k) {
    const set = new Set(); // Create a new set to store unique elements
    
    // Add elements from the array to the set
    for (let i = 0; i < arr.length; i++) {
        set.add(arr[i]);
    }
    
    let num = 1; // Current natural number
    
    while (k > 0) {
        if (set.has(num)) { // Check if the set contains the current number
            num++;
        } else {
            k--;
            num++;
        }
    }
    
    return num - 1; // Subtract 1 to get the k-th smallest number
}

// Driver Code
const arr = [1, 3];
const k = 4;
const kthSmallest = findKthSmallestNumber(arr, k);
console.log("K-th smallest number:", kthSmallest);

Output
K-th smallest number: 6

Time Complexity: It takes O(n) time to build a set by iterating through an array, where n is the size of the array.
Iterating through the natural numbers until the kth smallest number is reached takes O(k) time in the worst case.
Thus, the total time complexity is O(n + k).
Space Complexity: O(n), where n is the size of the array, as it can potentially store all the distinct elements of the array.
 

Counting Approach:

  • Create an array of size max+2, where max is the maximum number of elements in the given array.
  • Initialize all elements of the count array to 0 .
  • Increase the number of each element in the count array by iterating through the given array.
  • Start changing num to 1, which represents the current generation number.
    If k is greater than 0:
    If the number of nums in the count array is greater than 0, decrement the count by 1 and continue.
    If the count is 0, decrease k by 1 .
    Increase num by
  • Returns the num value as the k-th smallest number
     
C++
#include <iostream>
#include <algorithm>
using namespace std;

int findKthSmallestNumber(int arr[], int n, int k) {
    int max_num = *max_element(arr, arr + n);
    
    int* count = new int[max_num + 2]();
    for (int i = 0; i < n; i++) {
        count[arr[i]]++;
    }
    
    int num = 1; // Current natural number
    
    while (k > 0) {
        if (count[num] > 0) {
            count[num]--;
        } else {
            k--;
        }
        num++;
    }
    
    delete[] count;
    return num - 1; // Subtract 1 to get the k-th smallest number
}

int main() {
    int arr[] = {1, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 4;
    
    int kthSmallest = findKthSmallestNumber(arr, n, k);
    cout << "K-th smallest number: " << kthSmallest << endl;
    
    return 0;
}
Java
/*package whatever //do not write package name here */

public class KthSmallestNumber {
    
    public static void main(String[] args) {
        int[] arr = {1, 3};
        int k = 4;
        int kthSmallest = findKthSmallestNumber(arr, k);
        System.out.println("K-th smallest number: " + kthSmallest);
    }
    
    public static int findKthSmallestNumber(int[] arr, int k) {
        int max = Integer.MIN_VALUE;
        for (int num : arr) {
            max = Math.max(max, num);
        }
        
        int[] count = new int[max + 1]; // Updated size of count array
        
        for (int num : arr) {
            count[num]++;
        }
        
        int num = 1; // Current natural number
        
        while (k > 0) {
            if (num < count.length && count[num] > 0) { // Added boundary check
                count[num]--;
            } else {
                k--;
            }
            num++;
        }
        
        return num - 1; // Subtract 1 to get the k-th smallest number
    }
}

//This code is contributed by Sovi
Python3
def find_kth_smallest_number(arr, k):
    max_num = max(arr)
    
    count = [0] * (max_num + 1)  # Corrected size
    for num in arr:
        count[num] += 1
        
    num = 1  # Current natural number
    
    while k > 0:
        if num < len(count) and count[num] > 0:
            count[num] -= 1
        else:
            k -= 1
        num += 1
        
    return num - 1  # Subtract 1 to get the k-th smallest number

def main():
    arr = [1, 3]
    k = 4
    
    kth_smallest = find_kth_smallest_number(arr, k)
    print("K-th smallest number:", kth_smallest)

if __name__ == "__main__":
    main()
C#
using System;

public class KthSmallestNumber {
    public static void Main(string[] args)
    {
        int[] arr = { 1, 3 };
        int k = 4;
        int kthSmallest = FindKthSmallestNumber(arr, k);
        Console.WriteLine("K-th smallest number: "
                          + kthSmallest);
    }

    public static int FindKthSmallestNumber(int[] arr,
                                            int k)
    {
        int max = int.MinValue;
        foreach(int numValue in
                    arr) // Change variable name here
        {
            max = Math.Max(max, numValue);
        }

        int[] count
            = new int[max
                      + 1]; // Updated size of count array

        foreach(int numValue in
                    arr) // Change variable name here
        {
            count[numValue]++;
        }

        int currentNum = 1; // Current natural number

        while (k > 0) {
            if (currentNum < count.Length
                && count[currentNum]
                       > 0) // Added boundary check
            {
                count[currentNum]--;
            }
            else {
                k--;
            }
            currentNum++;
        }

        return currentNum - 1; // Subtract 1 to get the k-th
                               // smallest number
    }
}
JavaScript
function findKthSmallestNumber(arr, k) {
    let max = Number.MIN_VALUE;

    // Find the maximum value in the array
    for (let numValue of arr) {
        max = Math.max(max, numValue);
    }

    // Create an array to store the count of each number
    const count = new Array(max + 1).fill(0);

    // Count the occurrences of each number in the array
    for (let numValue of arr) {
        count[numValue]++;
    }

    let currentNum = 1; // Start with the smallest natural number

    while (k > 0) {
        if (currentNum < count.length && count[currentNum] > 0) {
            // If the currentNum is within the array bounds and has occurrences left
            count[currentNum]--;
        } else {
            // Otherwise, decrement k
            k--;
        }
        currentNum++;
    }

    // Subtract 1 to get the k-th smallest number
    return currentNum - 1;
}

const arr = [1, 3];
const k = 4;
const kthSmallest = findKthSmallestNumber(arr, k);
console.log("K-th smallest number: " + kthSmallest);

Output
K-th smallest number: 7

Time Complexity: It takes O(n) time to find the largest element in the array, where n is the size of the array.
When you start an accounting system, it takes O(n) time to count every occurrence in the system.
Iterating through the natural numbers until the kth smallest number is reached takes O(k) time in the worst case.
Thus, the total time complexity is O(n + k).


Space Complexity: O(n), where n is the size of the array.


More efficient method : K-th smallest element after removing given integers from natural numbers | Set 2
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 



Previous Article
Next Article

Similar Reads

K-th smallest element after removing given integers from natural numbers | Set 2
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. Examples: Input : arr[] = { 1 } and k = 1.Output: 2Natural numbers are {1, 2, 3, 4, .... }After removing {1}, we g
4 min read
Nth natural number after removing all numbers consisting of the digit 9
Given a positive integer N, the task is to find the Nth natural number after removing all the natural numbers containing digit 9. Examples: Input: N = 8Output: 8Explanation:Since 9 is the first natural number that contains the digit 9 and is the 9th natural number, therefore, no removal required to find the 8th natural number, which is 8. Input: N
8 min read
Minimum common sum from K arrays after removing some part of their suffix
Given K (K > 2) arrays of different sizes in a 2D list arr[][] where elements in each array are non-negative. Find the minimum common sum of K arrays after removing part of the suffix(possibly none) from each array. Examples: Input: K = 3, arr = {{5, 2, 4}, {1, 4, 1, 1}, {2, 3}}Output: 5Explanation: 1st array: [5, 5+2, 5+2+4], = {5, 7, 11} remov
7 min read
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order
Given two integers N and K, the task is to find the Kth element in the permutation of first N natural numbers arranged such that all the even numbers appear before the odd numbers in increasing order. Examples : Input: N = 10, K = 3 Output: 6Explanation:The required permutation is {2, 4, 6, 8, 10, 1, 3, 5, 7, 9}.The 3rd number in the permutation is
9 min read
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Output: 5Explanation:Initially, the array is {1, 2, 3,
7 min read
Find the last element after repeatedly removing every second element from either end alternately
Given an array arr[] consisting of N integers, the task is to find the last remaining array element after removing every second element, starting from the first and last alternately. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}Output: 8Explanation: Elements in the list are: 1 2 3 4 5 6 7 8 9 10Starting from first array element, removing
8 min read
Lexicographically smallest permutation of size A having B integers exceeding all preceding integers
Given two positive integers, A and B, the task is to generate the lexicographically smallest permutation of all integers up to A in which exactly B integers are greater than all its preceding elements. Examples: Input: A = 3, B = 2Output : [1, 3, 2]Explanation:All possible permutations of integers [1, 3] are [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3,
15 min read
Average of remaining elements after removing K largest and K smallest elements from array
Given an array of N integers. The task is to find the average of the numbers after removing k largest elements and k smallest element from the array i.e. calculate the average value of the remaining N - 2K elements. Examples: Input: arr = [1, 2, 4, 4, 5, 6], K = 2Output: 4Remove 2 smallest elements i.e. 1 and 2Remove 2 largest elements i.e. 5 and 6
5 min read
Queries to calculate average of an array after removing K smallest and largest elements with updates
Given two positive integers N and K, initialize an empty array arr[] and Q number of queries of the following two types: addInteger(x): Insert element X in the array arr[]. If the size of the array becomes greater than N, then remove the element from the beginning of the array.calculateSpecialAverage(): Find the average of array elements after remo
15+ min read
Finding the Nth term in a sequence formed by removing digit K from natural numbers
Given the integers N, K and an infinite sequence of natural numbers where all the numbers containing the digit K (1<=K<=9) are removed. The task is to return the Nth number of this sequence. Example: Input: N = 12, K = 2Output: 14Explanation: The sequence generated for the above input would be like this: 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14
10 min read
Find last element after deleting every second element in array of n integers
Given a circular array of size n containing integers from 1 to n. Find the last element that would remain in the list after erasing every second element starting from the first element. Example: Input: 5 Output: 3 Explanation Element in circular array are: 1 2 3 4 5 Starting from first element i.e, '1' delete every second element like this, 1 0 3 4
7 min read
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element
Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly. Examples: Input: arr[] = {3, 4, 2, 1}Output: 4Explanation:Operation 1: The array arr[] modifies to {4 - 3, 2 - 4, 1 - 2} = {1, -2, -1}.Operation
8 min read
Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2
Given an array arr[] consisting of N strings, the task is to sort the array in ascending order after modifying each string by removing all characters that are not perfect power of 2 and then sort the modified string in decreasing order. Examples: Input: arr[] = {"aaacbb", "geeks", "aaa"}Output: cbb skgeeExplanation:Following are the modified string
10 min read
Remaining array element after repeated removal of the smallest element from pairs with absolute difference of 2 or 0
Given an array arr[] consisting of N positive integers, the task is to check if it is possible to reduce the size of the array to 1 by repeatedly removing the smallest element from a pair having absolute difference of 2 or 0 between them. If it is not possible to reduce, then print "-1". Otherwise, print the last remaining element in the array. Exa
6 min read
Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements
Given an array arr[] consisting of N positive integers, the task is to find the last positive array element remaining after repeated subtractions of the smallest positive array element from all array elements. Examples: Input: arr[] = {3, 5, 4, 7}Output: 2Explanation: Subtract the smallest positive element from the array, i.e. 3, the new array is a
6 min read
Count L-length arrays possible made up of first N natural numbers and each element dividing the next element
Given two positive integers N and L, the task is to find the number of L-length arrays made up of first N natural numbers such that every element in the array divides its next element. Examples: Input: N = 3, L = 3Output: 7Explanation:Following arrays has elements from the range [1, 3] and each array element divides its next element: {1, 1, 1}{1, 1
13 min read
Check if there exists some positive integers X and Y such that P^X is equal to Q^Y
Given two integers P and Q, the task is to check whether a pair (P, Q) is equal or not, and a pair is said to be equal if there exist some positive integers X and Y such that PX = QY. Examples: Input: P = 16 , Q = 4Output: Yes?Explanation: Let X = 2 and Y = 4. Thus, PX = 162 = 256 and QY = 44 = 256 . Thus, the pair (16,4) is equal. Input: P = 12 ,
4 min read
Check whether each Array element can be reduced to minimum element by replacing it with remainder with some X
Given an array arr[] of non-negative integers, the task is to check whether all array elements can be reduced to the minimum element in the array by choosing any positive integer X and update an array element arr[i] to arr[i]%X. If it is possible to do so, then print Yes. Otherwise, print No. Examples: Input: arr[] = {1, 1, 3, 4}Output: YesExplanat
6 min read
Longest Prime Subarray after removing one element
Given an array A of integers. We can remove at most one index from the array. Our goal is to maximize the length of the subarray that contains all primes. Print the largest length subarray that you can achieve by removing exactly one element from the array . Examples: Input : arr[] = { 2, 8, 5, 7, 9, 5, 7 }Output : 4 Explanation : If we remove the
10 min read
Maximum length of Strictly Increasing Sub-array after removing at most one element
Given an array arr[], the task is to remove at most one element and calculate the maximum length of strictly increasing subarray. Examples: Input: arr[] = {1, 2, 5, 3, 4} Output: 4 After deleting 5, the resulting array will be {1, 2, 3, 4} and the maximum length of its strictly increasing subarray is 4. Input: arr[] = {1, 2} Output: 2 The complete
10 min read
Queries to find the maximum array element after removing elements from a given range
Given an array arr[] and an array Q[][] consisting of queries of the form of {L, R}, the task for each query is to find the maximum array element after removing array elements from the range of indices [L, R]. If the array becomes empty after removing the elements from given range of indices, then print 0. Examples: Input: arr[] = {5, 6, 8, 10, 15}
10 min read
Find Array after removing -1 and closest non-negative left element
Given an array arr[] of size N that contains -1 and all positive integers, the task is to modify the array and print the final array after performing the below valid operations: Choose -1 from the array.Remove the closest non-negative element (if there is any) to its left, as well as remove -1 itself. Examples: Input: arr[] = {1, 2, 3, -1, -1, 4, 5
11 min read
Pair of arrays with equal sum after removing exactly one element from each
Given K arrays of different size. The task is to check if there exist any two arrays which have the same sum of elements after removing exactly one element from each of them. (Any element can be removed, but exactly one has to be removed). Print the indices of the array and the index of the removed elements if such pairs exist. If there are multipl
10 min read
Maximize the maximum subarray sum after removing atmost one element
Given an array arr[] of N integers, the task is to find the maximum sum of a subarray with at most one deletion allowed. The size of subarray to be considered should be at least 1. Examples: Input: arr[] = {1, 2, 3, -2, 3} Output: 9 The maximum sub-array sum is given by the sub-array {2, 3, -2, 3} Hence, we can remove -2 to further maximize the sub
2 min read
Lexicographically smallest permutation of first N natural numbers having K perfect indices
Given two positive integers N and K, the task is to find lexicographically the smallest permutation of first N natural numbers such that there are exactly K perfect indices. An index i in an array is said to be perfect if all the elements at indices smaller than i are smaller than the element at index i. Examples: Input: N = 10, K = 3Output: 8 9 10
5 min read
Find the smallest value of N such that sum of first N natural numbers is ≥ X
Given a positive integer X (1 ? X ? 106), the task is to find the minimum value N, such that the sum of first N natural numbers is ? X. Examples: Input: X = 14Output: 5Explanation: Sum of first 5 natural numbers is 15 which is greater than X( = 14). 1 + 2 = 3( < 14)1 + 2 + 3 = 6( < 14)1 + 2 + 3 + 4 = 10( < 15)1 + 2 + 3 + 4 + 5 = 15( > 1
13 min read
Smallest value of N such that the sum of all natural numbers from K to N is at least X
Given two positive integers X and K, the task is to find the minimum value of N possible such that the sum of all natural numbers from the range [K, N] is at least X. If no possible value of N exists, then print -1. Examples: Input: K = 5, X = 13Output: 7Explanation: The minimum possible value is 7. Sum = 5 + 6 + 7 = 18, which is at least 13. Input
11 min read
Smallest number after n removals after k day
Given a set containing all the natural numbers till infinity. You have k days and an array arr, on each day you remove a[i]th smallest natural number from the set, the task is to tell the smallest number in the set after k days. Examples: Input: N = 5, K = 1, arr[] = {1, 2, 4, 5, 6}Output: 3 Input: N = 5, K = 3, arr = {1, 3, 5, 6, 7}Output: 9 Appro
5 min read
Count set bits in the Kth number after segregating even and odd from N natural numbers
Given two integers N and K, the task is to find the count of set bits in the Kth number in the Odd-Even sequence made of the number from the range [1, N]. The Odd-Even sequence first contains all the odd numbers from 1 to N and then all the even numbers from 1 to N.Examples: Input: N = 8, K = 4 Output: 3 The sequence is 1, 3, 5, 7, 2, 4, 6 and 8. 4
6 min read
Check if any value of x can be made equal to k after some operations
Given a number k, the task is to choose a positive number x(any) initially, such that the value of x can be made equal to k after some operations. The operation is to add x to the current score and double the value of x. Note that you need to perform this operation at least twice to change from k to x. Find this positive number x or return -1, if s
4 min read
Article Tags :
Practice Tags :