# Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal

• Last Updated : 17 Jan, 2022

Given an integer K and an array arr[] consisting of N integers, the task is to find the length of the subarray of smallest possible length to be removed such that the count of array elements smaller than and greater than K in the remaining array are equal.

Examples:

Input: arr[] = {5, 7, 2, 8, 7, 4, 5, 9}, K = 5
Output: 2
Explanation:
Smallest subarray required to be removed is {8, 7}, to make the largest resultant array {5, 7, 2, 4, 5, 9} satisfy the given condition.

Input: arr[] = {12, 16, 12, 13, 10}, K = 13
Output: 3
Explanation:
smallest subarray required to be removed is {12, 13, 10} to make the largest resultant array {12, 16} satisfy the given condition.

Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays, and traverse the remaining array, to keep count of array elements that are strictly greater than and smaller than integer K. Then, select the smallest subarray whose deletion gives an array having equal number of smaller and greater elements.

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

Efficient Approach: The idea is to use Hashing with some modification to the array to solve it in O(N) time. The given array can have 3 types of elements:

• element = K: change element to 0 (because we need elements, that are strictly greater than K or smaller than K)
• element > K: change element to 1
• element < K: change element to -1

Now, calculate the sum of all array elements and store it in a variable, say total_sum. Now, the total_sum can have three possible ranges of values:

• If total_sum = 0: all 1s are cancelled by -1s. So, equal number of greater and smaller elements than K are already present. No deletion operation is required. Hence, print 0 as the required answer.
• If total_sum > 0: some 1s are left uncancelled by -1s. i.e. array has more number of greater elements than K and less number of smaller elements than K. So, find the smallest subarray of sum = total_sum as it is the smallest subarray to be deleted.
• If total_sum < 0: some -1s are left uncancelled by 1s. i.e. array has more number of smaller elements than k and less number of greater elements than K. So, find the smallest subarray of sum = total_sum as it is the smallest subarray to be deleted.

Below is the implementation of the above approach:

## C++

 `// C++ Program to implement` `// the above approach`   `#include ` `using` `namespace` `std;`   `// Function ot find the length` `// of the smallest subarray` `int` `smallSubarray(``int` `arr[], ``int` `n,` `                  ``int` `total_sum)` `{` `    ``// Stores (prefix Sum, index)` `    ``// as (key, value) mappings` `    ``unordered_map<``int``, ``int``> m;` `    ``int` `length = INT_MAX;` `    ``int` `prefixSum = 0;`   `    ``// Iterate till N` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// Update the prefixSum` `        ``prefixSum += arr[i];`   `        ``// Update the length` `        ``if` `(prefixSum == total_sum) {` `            ``length = min(length, i + 1);` `        ``}`   `        ``// Put the latest index to` `        ``// find the minimum length` `        ``m[prefixSum] = i;`   `        ``if` `(m.count(prefixSum - total_sum)) {`   `            ``// Update the length` `            ``length` `                ``= min(length,` `                      ``i - m[prefixSum - total_sum]);` `        ``}` `    ``}`   `    ``// Return the answer` `    ``return` `length;` `}`   `// Function to find the length of` `// the largest subarray` `int` `smallestSubarrayremoved(``int` `arr[], ``int` `n,` `                            ``int` `k)` `{`   `    ``// Stores the sum of all array` `    ``// elements after modification` `    ``int` `total_sum = 0;`   `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// Change greater than k to 1` `        ``if` `(arr[i] > k) {` `            ``arr[i] = 1;` `        ``}`   `        ``// Change smaller than k to -1` `        ``else` `if` `(arr[i] < k) {` `            ``arr[i] = -1;` `        ``}`   `        ``// Change equal to k to 0` `        ``else` `{` `            ``arr[i] = 0;` `        ``}`   `        ``// Update total_sum` `        ``total_sum += arr[i];` `    ``}`   `    ``// No deletion required, return 0` `    ``if` `(total_sum == 0) {` `        ``return` `0;` `    ``}`   `    ``else` `{`   `        ``// Delete smallest subarray` `        ``// that has sum = total_sum` `        ``return` `smallSubarray(arr, n,` `                             ``total_sum);` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 12, 16, 12, 13, 10 };` `    ``int` `K = 13;`   `    ``int` `n = ``sizeof``(arr) / ``sizeof``(``int``);`   `    ``cout << smallestSubarrayremoved(` `        ``arr, n, K);`   `    ``return` `0;` `}`

## Java

 `// Java program to implement` `// the above approach` `import` `java.util.*;`   `class` `GFG{` `    `  `// Function ot find the length` `// of the smallest subarray` `static` `int` `smallSubarray(``int` `arr[], ``int` `n,` `                         ``int` `total_sum)` `{` `    `  `    ``// Stores (prefix Sum, index)` `    ``// as (key, value) mappings` `    ``Map m = ``new` `HashMap();` `                                 `  `    ``int` `length = Integer.MAX_VALUE;` `    ``int` `prefixSum = ``0``;` `    `  `    ``// Iterate till N` `    ``for``(``int` `i = ``0``; i < n; i++)` `    ``{` `        `  `        ``// Update the prefixSum` `        ``prefixSum += arr[i];` `        `  `        ``// Update the length` `        ``if` `(prefixSum == total_sum)` `        ``{` `            ``length = Math.min(length, i + ``1``);` `        ``}` `        `  `        ``// Put the latest index to` `        ``// find the minimum length` `        ``m.put(prefixSum, i);` `        `  `        ``if` `(m.containsKey(prefixSum - total_sum))` `        ``{` `            `  `            ``// Update the length` `            ``length = Math.min(length,` `                              ``i - m.get(prefixSum - ` `                                        ``total_sum));` `        ``}` `    ``}` `    `  `    ``// Return the answer` `    ``return` `length;` `}`   `// Function to find the length of` `// the largest subarray` `static` `int` `smallestSubarrayremoved(``int` `arr[], ``int` `n,` `                                   ``int` `k)` `{` `    `  `    ``// Stores the sum of all array` `    ``// elements after modification` `    ``int` `total_sum = ``0``;` `    `  `    ``for``(``int` `i = ``0``; i < n; i++)` `    ``{` `        `  `        ``// Change greater than k to 1` `        ``if` `(arr[i] > k)` `        ``{` `            ``arr[i] = ``1``;` `        ``}` `        `  `        ``// Change smaller than k to -1` `        ``else` `if` `(arr[i] < k)` `        ``{` `            ``arr[i] = -``1``;` `        ``}` `        `  `        ``// Change equal to k to 0` `        ``else` `        ``{` `            ``arr[i] = ``0``;` `        ``}` `        `  `        ``// Update total_sum` `        ``total_sum += arr[i];` `    ``}` `    `  `    ``// No deletion required, return 0` `    ``if` `(total_sum == ``0``)` `    ``{` `        ``return` `0``;` `    ``}` `    ``else` `    ``{` `        `  `        ``// Delete smallest subarray` `        ``// that has sum = total_sum` `        ``return` `smallSubarray(arr, n, total_sum);` `    ``}` `}`   `// Driver Code` `public` `static` `void` `main(String[] args)` `{` `    ``int` `arr[] = { ``12``, ``16``, ``12``, ``13``, ``10` `};` `    ``int` `K = ``13``;` `    ``int` `n = arr.length;` `    `  `    ``System.out.println(` `        ``smallestSubarrayremoved(arr, n, K));` `}` `}`   `// This code is contributed by chitranayal`

## Python3

 `# Python3 program to implement` `# the above approach` `import` `sys`   `# Function ot find the length` `# of the smallest subarray` `def` `smallSubarray(arr, n, total_sum):`   `    ``# Stores (prefix Sum, index)` `    ``# as (key, value) mappings` `    ``m ``=` `{}` `    ``length ``=` `sys.maxsize` `    ``prefixSum ``=` `0`   `    ``# Iterate till N` `    ``for` `i ``in` `range``(n):`   `        ``# Update the prefixSum` `        ``prefixSum ``+``=` `arr[i]`   `        ``# Update the length` `        ``if``(prefixSum ``=``=` `total_sum):` `            ``length ``=` `min``(length, i ``+` `1``)`   `        ``# Put the latest index to` `        ``# find the minimum length` `        ``m[prefixSum] ``=` `i`   `        ``if``((prefixSum ``-` `total_sum) ``in` `m.keys()):`   `            ``# Update the length` `            ``length ``=` `min``(length,` `                         ``i ``-` `m[prefixSum ``-` `total_sum])`   `    ``# Return the answer` `    ``return` `length`   `# Function to find the length of` `# the largest subarray` `def` `smallestSubarrayremoved(arr, n, k):`   `    ``# Stores the sum of all array` `    ``# elements after modification` `    ``total_sum ``=` `0`   `    ``for` `i ``in` `range``(n):`   `        ``# Change greater than k to 1` `        ``if``(arr[i] > k):` `            ``arr[i] ``=` `1`   `        ``# Change smaller than k to -1` `        ``elif``(arr[i] < k):` `            ``arr[i] ``=` `-``1`   `        ``# Change equal to k to 0` `        ``else``:` `            ``arr[i] ``=` `0`   `        ``# Update total_sum` `        ``total_sum ``+``=` `arr[i]`   `    ``# No deletion required, return 0` `    ``if``(total_sum ``=``=` `0``):` `        ``return` `0` `    ``else``:` `        `  `        ``# Delete smallest subarray` `        ``# that has sum = total_sum` `        ``return` `smallSubarray(arr, n,` `                             ``total_sum)` `                             `  `# Driver Code` `arr ``=` `[ ``12``, ``16``, ``12``, ``13``, ``10` `]` `K ``=` `13`   `n ``=` `len``(arr)`   `# Function call` `print``(smallestSubarrayremoved(arr, n, K))`   `# This code is contributed by Shivam Singh`

## C#

 `// C# program to implement` `// the above approach` `using` `System;` `using` `System.Collections.Generic;` `class` `GFG{` `    `  `// Function ot find the length` `// of the smallest subarray` `static` `int` `smallSubarray(``int` `[]arr, ``int` `n,` `                         ``int` `total_sum)` `{` `    `  `    ``// Stores (prefix Sum, index)` `    ``// as (key, value) mappings` `    ``Dictionary<``int``,` `               ``int``> m = ``new` `Dictionary<``int``,` `                                       ``int``>();` `                                 `  `    ``int` `length = ``int``.MaxValue;` `    ``int` `prefixSum = 0;` `    `  `    ``// Iterate till N` `    ``for``(``int` `i = 0; i < n; i++)` `    ``{` `        `  `        ``// Update the prefixSum` `        ``prefixSum += arr[i];` `        `  `        ``// Update the length` `        ``if` `(prefixSum == total_sum)` `        ``{` `            ``length = Math.Min(length, i + 1);` `        ``}` `        `  `        ``// Put the latest index to` `        ``// find the minimum length` `        ``if` `(m.ContainsKey(prefixSum))` `            ``m[prefixSum] = i;` `        ``else` `            ``m.Add(prefixSum, i);` `        `  `        ``if` `(m.ContainsKey(prefixSum - total_sum))` `        ``{` `            `  `            ``// Update the length` `            ``length = Math.Min(length,` `                              ``i - m[prefixSum - ` `                                    ``total_sum]);` `        ``}` `    ``}` `    `  `    ``// Return the answer` `    ``return` `length;` `}`   `// Function to find the length of` `// the largest subarray` `static` `int` `smallestSubarrayremoved(``int` `[]arr, ` `                                   ``int` `n, ``int` `k)` `{` `    `  `    ``// Stores the sum of all array` `    ``// elements after modification` `    ``int` `total_sum = 0;` `    `  `    ``for``(``int` `i = 0; i < n; i++)` `    ``{` `        `  `        ``// Change greater than k to 1` `        ``if` `(arr[i] > k)` `        ``{` `            ``arr[i] = 1;` `        ``}` `        `  `        ``// Change smaller than k to -1` `        ``else` `if` `(arr[i] < k)` `        ``{` `            ``arr[i] = -1;` `        ``}` `        `  `        ``// Change equal to k to 0` `        ``else` `        ``{` `            ``arr[i] = 0;` `        ``}` `        `  `        ``// Update total_sum` `        ``total_sum += arr[i];` `    ``}` `    `  `    ``// No deletion required, return 0` `    ``if` `(total_sum == 0)` `    ``{` `        ``return` `0;` `    ``}` `    ``else` `    ``{` `        `  `        ``// Delete smallest subarray` `        ``// that has sum = total_sum` `        ``return` `smallSubarray(arr, n, total_sum);` `    ``}` `}`   `// Driver Code` `public` `static` `void` `Main(String[] args)` `{` `    ``int` `[]arr = { 12, 16, 12, 13, 10 };` `    ``int` `K = 13;` `    ``int` `n = arr.Length;` `    `  `    ``Console.WriteLine(` `            ``smallestSubarrayremoved(arr, n, K));` `}` `}`   `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output:

`3`

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :