Given an array arr[] of size n and an integer k, remove the minimum number of elements such that the difference between the maximum and minimum remaining elements is at most k.
Examples:
Input : arr[] = [1, 3, 4, 9, 10, 11, 12, 17, 20], k = 4
Output : 5
Explanation: Remove 1, 3, 4 from beginning and 17, 20 from the end.Input : arr[] = [1, 5, 6, 2, 8], K=2
Output : 3
Explanation: There are multiple ways to remove elements in this case. One among them is to remove 5, 6, 8. The other is to remove 1, 2, 5
Table of Content
[Naive Approach] Using Sorting + Binary Search – O(n log n) Time and O(1) Space
The idea is to first sort the array. After sorting we traverse it and for every index
i, we use binary search to find the farthest valid indexjsatisfyingarr[j] - arr[i] <= k. The remaining elements outside this range must be removed, and we minimize this count over all choices.
- Sort the array in ascending order
- For each index, use binary search to find the farthest valid element within difference
k - Calculate removals as total elements outside the valid subarray
- Track and return the minimum removals among all ranges
#include <bits/stdc++.h>
using namespace std;
// Function to find
// rightmost index
// which satisfies the condition
// arr[j] - arr[i] <= k
int findInd(int key, int i,
int n, int k, vector<int>& arr)
{
int start, end, mid, ind = -1;
// Initialising start to i + 1
start = i + 1;
// Initialising end to n - 1
end = n - 1;
// Binary search implementation
// to find the rightmost element
// that satisfy the condition
while (start <= end)
{
mid = start + (end - start) / 2;
// Check if the condition satisfies
if (arr[mid] - key <= k)
{
// Store the position
ind = mid;
// Make start = mid + 1
start = mid + 1;
}
else
{
// Make end = mid - 1
end = mid - 1;
}
}
// Return the rightmost position
return ind;
}
// Function to calculate
// minimum number of elements
// to be removed
int removals(vector<int>& arr, int k)
{
int n = arr.size();
int i, j, ans = n - 1;
// Sort the given array
sort(arr.begin(), arr.end());
// Iterate from 0 to n-1
for (i = 0; i < n; i++)
{
// Find j such that
// arr[j] - arr[i] <= k
j = findInd(arr[i], i, n, k, arr);
// If there exist such j
// that satisfies the condition
if (j != -1)
{
// Number of elements
// to be removed for this
// particular case is
// n - (j - i + 1)
ans = min(ans, n - (j - i + 1));
}
}
// Return answer
return ans;
}
// Driver Code
int main()
{
vector<int> arr = {1, 3, 4, 9, 10,
11, 12, 17, 20};
int k = 4;
cout << removals(arr, k);
return 0;
}
import java.util.*;
public class GfG {
// Function to find
// rightmost index
// which satisfies the condition
// arr[j] - arr[i] <= k
static int findInd(int key, int i, int n, int k,
int[] arr)
{
int start, end, mid, ind = -1;
// Initialising start to i + 1
start = i + 1;
// Initialising end to n - 1
end = n - 1;
// Binary search implementation
// to find the rightmost element
// that satisfy the condition
while (start <= end) {
mid = start + (end - start) / 2;
// Check if the condition satisfies
if (arr[mid] - key <= k) {
// Store the position
ind = mid;
// Make start = mid + 1
start = mid + 1;
}
else {
// Make end = mid - 1
end = mid - 1;
}
}
// Return the rightmost position
return ind;
}
// Function to calculate
// minimum number of elements
// to be removed
static int removals(int[] arr, int n, int k)
{
int i, j, ans = n - 1;
// Sort the given array
Arrays.sort(arr);
// Iterate from 0 to n-1
for (i = 0; i < n; i++) {
// Find j such that
// arr[j] - arr[i] <= k
j = findInd(arr[i], i, n, k, arr);
// If there exist such j
// that satisfies the condition
if (j != -1) {
// Number of elements
// to be removed for this
// particular case is
// n - (j - i + 1)
ans = Math.min(ans, n - (j - i + 1));
}
}
// Return answer
return ans;
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 1, 3, 4, 9, 10, 11, 12, 17, 20 };
int k = 4;
int n = arr.length;
System.out.println(removals(arr, n, k));
}
}
# Function to find
# rightmost index
# which satisfies the condition
# arr[j] - arr[i] <= k
def findInd(key, i, n, k, arr):
# Initialising start to i + 1
start = i + 1
# Initialising end to n - 1
end = n - 1
ind = i
# Binary search implementation
# to find the rightmost element
# that satisfy the condition
while start <= end:
mid = start + (end - start) // 2
# Check if the condition satisfies
if arr[mid] - key <= k:
# Store the position
ind = mid
# Make start = mid + 1
start = mid + 1
else:
# Make end = mid - 1
end = mid - 1
# Return the rightmost position
return ind
# Function to calculate
# minimum number of elements
# to be removed
def removals(arr, n, k):
ans = n - 1
# Sort the given array
arr.sort()
# Iterate from 0 to n-1
for i in range(n):
# Find j such that
# arr[j] - arr[i] <= k
j = findInd(arr[i], i, n, k, arr)
# Number of elements
# to be removed for this
# particular case is
# n - (j - i + 1)
ans = min(ans, n - (j - i + 1))
# Return answer
return ans
# Driver Code
if __name__ == "__main__":
arr = [1, 3, 4, 9, 10, 11, 12, 17, 20]
k = 4
n = len(arr)
print(removals(arr, n, k))
using System;
public class GfG {
// Function to find
// rightmost index
// which satisfies the condition
// arr[j] - arr[i] <= k
static int findInd(int key, int i,
int n, int k, int[] arr)
{
int start, end, mid, ind = -1;
// Initialising start to i + 1
start = i + 1;
// Initialising end to n - 1
end = n - 1;
// Binary search implementation
// to find the rightmost element
// that satisfy the condition
while (start <= end)
{
mid = start + (end - start) / 2;
// Check if the condition satisfies
if (arr[mid] - key <= k)
{
// Store the position
ind = mid;
// Make start = mid + 1
start = mid + 1;
}
else
{
// Make end = mid - 1
end = mid - 1;
}
}
// Return the rightmost position
return ind;
}
// Function to calculate
// minimum number of elements
// to be removed
static int removals(int[] arr, int n, int k)
{
int i, j, ans = n - 1;
// Sort the given array
Array.Sort(arr);
// Iterate from 0 to n-1
for (i = 0; i < n; i++)
{
// Find j such that
// arr[j] - arr[i] <= k
j = findInd(arr[i], i, n, k, arr);
// If there exist such j
// that satisfies the condition
if (j != -1)
{
// Number of elements
// to be removed for this
// particular case is
// n - (j - i + 1)
ans = Math.Min(ans, n - (j - i + 1));
}
}
// Return answer
return ans;
}
// Driver Code
public static void Main()
{
int[] arr = {1, 3, 4, 9, 10,
11, 12, 17, 20};
int k = 4;
int n = arr.Length;
Console.WriteLine(removals(arr, n, k));
}
}
function findInd(key, i, n, k, arr) {
let start, end, mid, ind = -1;
// Initialising start to i + 1
start = i + 1;
// Initialising end to n - 1
end = n - 1;
// Binary search implementation
// to find the rightmost element
// that satisfy the condition
while (start <= end) {
mid = Math.floor(start + (end - start) / 2);
// Check if the condition satisfies
if (arr[mid] - key <= k) {
// Store the position
ind = mid;
// Make start = mid + 1
start = mid + 1;
}
else {
// Make end = mid - 1
end = mid - 1;
}
}
// Return the rightmost position
return ind;
}
// Function to calculate
// minimum number of elements
// to be removed
function removals(arr, k) {
let n = arr.length;
let i, j, ans = n - 1;
// Sort the given array
arr.sort((a, b) => a - b);
// Iterate from 0 to n-1
for (i = 0; i < n; i++) {
// Find j such that
// arr[j] - arr[i] <= k
j = findInd(arr[i], i, n, k, arr);
// If there exist such j
// that satisfies the condition
if (j!= -1) {
// Number of elements
// to be removed for this
// particular case is
// n - (j - i + 1)
ans = Math.min(ans, n - (j - i + 1));
}
}
// Return answer
return ans;
}
// Driver Code
let arr = [1, 3, 4, 9, 10, 11, 12, 17, 20];
let k = 4;
console.log(removals(arr, k));
Output
5
[Expected Approach] Using Sorting + Sliding Window – O(n log n) Time and O(1) Space
We first sort the array After sorting, we use sliding window technique to maintain a valid range. If the difference exceeds
k, we move the left pointer forward until the condition becomes valid again. The minimum removals are the elements outside the largest valid window.
- Sort the array in ascending order
- Use two pointers to maintain a valid window with difference
<= k - If the difference exceeds
k, move the left pointer forward - Track the maximum valid window length and return
n - maxLen
#include<bits/stdc++.h>
using namespace std;
int removals(vector<int>& arr, int k)
{
int n = arr.size();
// Sort the Array
sort(arr.begin(), arr.end());
// to store the max length of
// array with difference <= k
int maxLen = 0;
int i = 0;
// J goes from 0 to n-1
for (int j = 0; j < n; j++) {
// if subarray difference exceeds k
// change starting position
while (arr[j] - arr[i] > k) {
i++;
}
// store maximum valid window length
maxLen = max(maxLen, j - i + 1);
}
// no. of elements need to be removed is
// Length of array - max subarray with diff <= k
return n - maxLen;
}
// Driver Code
int main()
{
vector<int> arr = {1, 3, 4, 9, 10, 11, 12, 17, 20};
int k = 4;
cout << removals(arr, k);
return 0;
}
import java.util.Arrays;
public class GfG {
public static int removals(int[] arr, int n, int k) {
// Sort the Array
Arrays.sort(arr);
// to store the max length of
// array with difference <= k
int maxLen = 0;
int i = 0;
// J goes from 0 to n-1
for (int j = 0; j < n; j++) {
// if subarray difference exceeds k
// change starting position
while (arr[j] - arr[i] > k) {
i++;
}
// store maximum valid window length
maxLen = Math.max(maxLen, j - i + 1);
}
// no. of elements need to be removed is
// Length of array - max subarray with diff <= k
return n - maxLen;
}
public static void main(String[] args) {
int[] arr = {1, 3, 4, 9, 10, 11, 12, 17, 20};
int k = 4;
int n = arr.length;
System.out.println(removals(arr, n, k));
}
}
from typing import List
def removals(arr: List[int], n: int, k: int) -> int:
# Sort the Array
arr.sort()
# to store the max length of
# array with difference <= k
maxLen = 0
i = 0
# J goes from 0 to n-1
for j in range(n):
# if subarray difference exceeds k
# change starting position
while arr[j] - arr[i] > k:
i += 1
# store maximum valid window length
maxLen = max(maxLen, j - i + 1)
# no. of elements need to be removed is
# Length of array - max subarray with diff <= k
return n - maxLen
# Driver Code
if __name__ == "__main__":
arr = [1, 3, 4, 9, 10, 11, 12, 17, 20]
k = 4
n = len(arr)
print(removals(arr, n, k))
using System;
public class GfG
{
public static int removals(int[] arr, int n, int k)
{
// Sort the Array
Array.Sort(arr);
// to store the max length of
// array with difference <= k
int maxLen = 0;
int i = 0;
// J goes from 0 to n-1
for (int j = 0; j < n; j++) {
// if subarray difference exceeds k
// change starting position
while (arr[j] - arr[i] > k) {
i++;
}
// store maximum valid window length
maxLen = Math.Max(maxLen, j - i + 1);
}
// no. of elements need to be removed is
// Length of array - max subarray with diff <= k
return n - maxLen;
}
public static void Main()
{
int[] arr = { 1, 3, 4, 9, 10, 11, 12, 17, 20 };
int k = 4;
int n = arr.Length;
Console.WriteLine(removals(arr, n, k));
}
}
function removals(arr, n, k) {
// Sort the Array
arr.sort((a, b) => a - b);
// to store the max length of
// array with difference <= k
let maxLen = 0;
let i = 0;
// J goes from 0 to n-1
for (let j = 0; j < n; j++) {
// if subarray difference exceeds k
// change starting position
while (arr[j] - arr[i] > k) {
i++;
}
// store maximum valid window length
maxLen = Math.max(maxLen, j - i + 1);
}
// no. of elements need to be removed is
// Length of array - max subarray with diff <= k
return n - maxLen;
}
// Driver Code
let arr = [1, 3, 4, 9, 10, 11, 12, 17, 20];
let k = 4;
let n = arr.length;
console.log(removals(arr, n, k));
Output
5