Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find the index of the smallest element to be removed to make sum of array divisible by K
Next article icon

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

Last Updated : 17 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 <bits/stdc++.h>
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<Integer,
        Integer> m = new HashMap<Integer,
                                 Integer>();
                                  
    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




<script>
// Javascript program to implement
// the above approach
 
// Function ot find the length
// of the smallest subarray
function smallSubarray(arr,n,total_sum)
{
    // Stores (prefix Sum, index)
    // as (key, value) mappings
    let m = new Map();
                                   
    let length = Number.MAX_VALUE;
    let prefixSum = 0;
      
    // Iterate till N
    for(let 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.set(prefixSum, i);
          
        if (m.has(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
function smallestSubarrayremoved(arr,n,k)
{
    // Stores the sum of all array
    // elements after modification
    let total_sum = 0;
      
    for(let 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
let arr=[12, 16, 12, 13, 10];
let K = 13;
let n = arr.length;
document.write(smallestSubarrayremoved(arr, n, K));
 
 
// This code is contributed by avanitrachhadiya2155
</script>
 
 
Output: 
3

 

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



Next Article
Find the index of the smallest element to be removed to make sum of array divisible by K

J

jigyansu
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • cpp-unordered_map
  • Hash
  • prefix-sum
  • subarray
Practice Tags :
  • Arrays
  • Hash
  • Hash
  • Mathematical
  • prefix-sum

Similar Reads

  • Length of smallest subarray required to be removed to make remaining elements consecutive
    Given an array arr[] consisting of N integers, the task is to find the length of the smallest subarray required to be removed to make the remaining array elements consecutive. Examples: Input: arr[] = {1, 2, 3, 7, 5, 4, 5}Output: 2Explanation:Removing the subarray {7, 5} from the array arr[] modifie
    15+ min read
  • Smallest subarray having an element with frequency greater than that of other elements
    Given an array arr of positive integers, the task is to find the smallest length subarray of length more than 1 having an element occurring more times than any other element. Examples: Input: arr[] = {2, 3, 2, 4, 5} Output: 2 3 2 Explanation: The subarray {2, 3, 2} has an element 2 which occurs more
    15+ min read
  • Find the index of the smallest element to be removed to make sum of array divisible by K
    Given an array arr[] of size N and a positive integer K, the task is to find the index of the smallest array element required to be removed to make the sum of remaining array divisible by K. If multiple solutions exist, then print the smallest index. Otherwise, print -1. Examples: Input: arr[ ] = {6
    8 min read
  • Length of smallest subarray to be removed to make sum of remaining elements divisible by K
    Given an array arr[] of integers and an integer K, the task is to find the length of the smallest subarray that needs to be removed such that the sum of remaining array elements is divisible by K. Removal of the entire array is not allowed. If it is impossible, then print "-1". Examples: Input: arr[
    11 min read
  • Smallest subarray from a given Array with sum greater than or equal to K | Set 2
    Given an array A[] consisting of N positive integers and an integer K, the task is to find the length of the smallest subarray with a sum greater than or equal to K. If no such subarray exists, print -1. Examples: Input: arr[] = {3, 1, 7, 1, 2}, K = 11Output: 3Explanation:The smallest subarray with
    15+ min read
  • Minimum length of the subarray required to be replaced to make frequency of array elements equal to N / M
    Given an array arr[] of size N consisting of only the first M natural numbers, the task is to find the minimum length of the subarray that is required to be replaced such that the frequency of array elements is N / M. Note: N is a multiple of M. Examples: Input: M = 3, arr[] = {1, 1, 1, 1, 2, 3}Outp
    10 min read
  • Smallest subarray such that all elements are greater than K
    Given an array of N integers and a number K, the task is to find the length of the smallest subarray in which all the elements are greater than K. If there is no such subarray possible, then print -1. Examples: Input: a[] = {3, 4, 5, 6, 7, 2, 10, 11}, K = 5 Output: 1 The subarray is {10} Input: a[]
    4 min read
  • Number of subarrays with at-least K size and elements not greater than M
    Given an array of N elements, K is the minimum size of the sub-array, and M is the limit of every element in the sub-array, the task is to count the number of sub-arrays with a minimum size of K and all the elements are lesser than or equal to M. Examples: Input: arr[] = {-5, 0, -10}, K = 1, M = 15O
    7 min read
  • Count non-overlapping Subarrays of size K with equal alternate elements
    Given an array arr[] of length N, the task is to find the count of non-overlapping subarrays of size K such that the alternate elements are equal. Examples: Input: arr[] = {2, 4, 2, 7}, K = 3Output: 1Explanation: Given subarray {2, 4, 2} is a valid array because the elements in even position(index n
    7 min read
  • Length of smallest subarray to be removed such that the remaining array is sorted
    Given an array arr[] consisting of N integers, the task is to print the length of the smallest subarray to be removed from arr[] such that the remaining array is sorted. Examples: Input: arr[] = {1, 2, 3, 10, 4, 2, 3, 5}Output: 3Explanation:The smallest subarray to be remove is {10, 4, 2} of length
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences