Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Maximize minimum sweetness in cake cutting
Next article icon

Find minimum subarray length to reduce frequency

Last Updated : 22 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k.

Examples:

Input: n = 4, arr[] = {3, 1, 3, 6}, k = 1
Output: 1
Explanation:  We can see that only 3 is having frequency 2 that is greater than k. So we can remove the 3 at the start of the array to that frequency of all elements become less than or equal to k. Thus the minimum length of the subarray to be removed is 1.

Input: n = 6, arr[] = {1, 2, 3, 3, 2, 1}, k = 1
Output: 3
Explanation: We Can remove the subarray {1, 2, 3} which is the minimum possible length subarray after being removed making the frequency of remaining elements less than or equal to k. 

Approach: This can be solved with the following idea:

This problem can be solved using Binary Search and Sliding Window Technique.

Below are the steps involved in the implementation of the code:

  • Create a Hash Table to store the frequency of the elements of the given array.
  • Create a variable cnt to store the count of numbers to be removed for satisfying the condition that the frequency of remaining elements after removing the subarray becomes less than or equal to k.
  • Store the frequency of the array elements in the Hash table.
  • If the frequency of an element becomes greater than k then increment cnt.
  • Now the subarray size lies in the range [0, n] where n is the array length. So we can apply binary search to it.
  • Initialize the answer as n.
  • Find the mid element on every iteration of binary search and create a window of size mid and check if it is possible that removing this window size from the array can make cnt equal to zero.
  • If it is possible update the answer as a minimum of answer and mid and now reduce the search space to [left, mid-1] to find if a smaller length is possible.
  • If it is not possible then reduce the search space to [mid+1, r] to find for larger length than mid.
  • After the end of the binary search, we will get the required answer.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h> using namespace std;  // Function to find minimum length // needed to be removed int minLength(int n, int k, vector<int>& arr) {      // Map to keep the count of     // Frequency     unordered_map<int, int> f;      int cnt = 0;     for (int i = 0; i < n; i++) {         f[arr[i]]++;         if (f[arr[i]] > k)             cnt++;     }      int l = 0, r = n;     int ans = n;      // Binary search     while (l <= r) {         int mid = l + (r - l) / 2;         for (int i = 0; i < mid; i++) {             if (f[arr[i]] > k)                 cnt--;             f[arr[i]]--;         }         if (cnt == 0) {             ans = min(ans, mid);             r = mid - 1;             for (int i = 0; i < mid; i++) {                 f[arr[i]]++;                 if (f[arr[i]] > k)                     cnt++;             }             continue;         }         bool flag = false;          // If particular length is possible         for (int i = mid; i < n; i++) {             if (f[arr[i - mid]] >= k)                 cnt++;             f[arr[i - mid]]++;              if (f[arr[i]] > k)                 cnt--;             f[arr[i]]--;              if (cnt == 0) {                 for (int j = i - mid + 1; j <= i; j++) {                     f[arr[j]]++;                     if (f[arr[j]] > k)                         cnt++;                 }                 flag = true;                 break;             }         }         if (flag) {             ans = min(ans, mid);             r = mid - 1;         }         else {             l = mid + 1;             for (int i = n - mid; i < n; i++) {                 f[arr[i]]++;                 if (f[arr[i]] > k)                     cnt++;             }         }     }      // Return the ans     return ans; }  // Driver code int main() {     int n = 4;     int k = 1;     vector<int> arr = { 3, 1, 2, 3 };      // Function call     cout << minLength(n, k, arr);     return 0; } 
Java
import java.util.HashMap; import java.util.Map; import java.util.Vector;  class GFG {     // Function to find minimum length     // needed to be removed     static int minLength(int n, int k, Vector<Integer> arr) {          // Map to keep the count of Frequency         Map<Integer, Integer> f = new HashMap<>();          int cnt = 0;         for (int i = 0; i < n; i++) {             f.put(arr.get(i), f.getOrDefault(arr.get(i), 0) + 1);             if (f.get(arr.get(i)) > k)                 cnt++;         }          int l = 0, r = n;         int ans = n;          // Binary search         while (l <= r) {             int mid = l + (r - l) / 2;             for (int i = 0; i < mid; i++) {                 if (f.get(arr.get(i)) > k)                     cnt--;                 f.put(arr.get(i), f.get(arr.get(i)) - 1);             }             if (cnt == 0) {                 ans = Math.min(ans, mid);                 r = mid - 1;                 for (int i = 0; i < mid; i++) {                     f.put(arr.get(i), f.get(arr.get(i)) + 1);                     if (f.get(arr.get(i)) > k)                         cnt++;                 }                 continue;             }             boolean flag = false;              // If particular length is possible             for (int i = mid; i < n; i++) {                 if (f.get(arr.get(i - mid)) >= k)                     cnt++;                 f.put(arr.get(i - mid), f.get(arr.get(i - mid)) + 1);                  if (f.get(arr.get(i)) > k)                     cnt--;                 f.put(arr.get(i), f.get(arr.get(i)) - 1);                  if (cnt == 0) {                     for (int j = i - mid + 1; j <= i; j++) {                         f.put(arr.get(j), f.get(arr.get(j)) + 1);                         if (f.get(arr.get(j)) > k)                             cnt++;                     }                     flag = true;                     break;                 }             }             if (flag) {                 ans = Math.min(ans, mid);                 r = mid - 1;             } else {                 l = mid + 1;                 for (int i = n - mid; i < n; i++) {                     f.put(arr.get(i), f.get(arr.get(i)) + 1);                     if (f.get(arr.get(i)) > k)                         cnt++;                 }             }         }          // Return the ans         return ans;     }     // Nikunj Sonigara     public static void main(String[] args) {         int n = 4;         int k = 1;         Vector<Integer> arr = new Vector<>(4);         arr.add(3);         arr.add(1);         arr.add(2);         arr.add(3);          // Function call         System.out.println(minLength(n, k, arr));     } } 
Python3
# Python code for the above approach from typing import List from collections import defaultdict  # Function to find minimum length needed to be removed def min_length(n: int, k: int, arr: List[int]) -> int:      # Dictionary to keep the count of frequency     f = defaultdict(int)      cnt = 0     for i in range(n):         f[arr[i]] += 1         if f[arr[i]] > k:             cnt += 1      l = 0     r = n     ans = n      # Binary search     while l <= r:         mid = l + (r - l) // 2         for i in range(mid):             if f[arr[i]] > k:                 cnt -= 1             f[arr[i]] -= 1         if cnt == 0:             ans = min(ans, mid)             r = mid - 1             for i in range(mid):                 f[arr[i]] += 1                 if f[arr[i]] > k:                     cnt += 1             continue         flag = False          # If a particular length is possible         for i in range(mid, n):             if f[arr[i - mid]] >= k:                 cnt += 1             f[arr[i - mid]] += 1              if f[arr[i]] > k:                 cnt -= 1             f[arr[i]] -= 1              if cnt == 0:                 for j in range(i - mid + 1, i + 1):                     f[arr[j]] += 1                     if f[arr[j]] > k:                         cnt += 1                 flag = True                 break         if flag:             ans = min(ans, mid)             r = mid - 1         else:             l = mid + 1             for i in range(n - mid, n):                 f[arr[i]] += 1                 if f[arr[i]] > k:                     cnt += 1      # Return the answer     return ans  # Driver code if __name__ == "__main__":     n = 4     k = 1     arr = [3, 1, 2, 3]      # Function call     print(min_length(n, k, arr)) 
C#
// c# code for the above approach  using System; using System.Collections.Generic;  class GFG {     // Function to find minimum length     // needed to be removed     static int MinLength(int n, int k, List<int> arr)     {         // Dictionary to keep the count of Frequency         Dictionary<int, int> f = new Dictionary<int, int>();          int cnt = 0;         for (int i = 0; i < n; i++)         {             if (f.ContainsKey(arr[i]))                 f[arr[i]]++;             else                 f[arr[i]] = 1;              if (f[arr[i]] > k)                 cnt++;         }          int l = 0, r = n;         int ans = n;          // Binary search         while (l <= r)         {             int mid = l + (r - l) / 2;             for (int i = 0; i < mid; i++)             {                 if (f[arr[i]] > k)                     cnt--;                  f[arr[i]]--;             }              if (cnt == 0)             {                 ans = Math.Min(ans, mid);                 r = mid - 1;                  for (int i = 0; i < mid; i++)                 {                     f[arr[i]]++;                     if (f[arr[i]] > k)                         cnt++;                 }                  continue;             }              bool flag = false;              // If a particular length is possible             for (int i = mid; i < n; i++)             {                 if (f[arr[i - mid]] >= k)                     cnt++;                  f[arr[i - mid]]++;                  if (f[arr[i]] > k)                     cnt--;                  f[arr[i]]--;                  if (cnt == 0)                 {                     for (int j = i - mid + 1; j <= i; j++)                     {                         f[arr[j]]++;                         if (f[arr[j]] > k)                             cnt++;                     }                      flag = true;                     break;                 }             }              if (flag)             {                 ans = Math.Min(ans, mid);                 r = mid - 1;             }             else             {                 l = mid + 1;                  for (int i = n - mid; i < n; i++)                 {                     f[arr[i]]++;                     if (f[arr[i]] > k)                         cnt++;                 }             }         }          // Return the ans         return ans;     }      // Nikunj Sonigara     public static void Main(string[] args)     {         int n = 4;         int k = 1;         List<int> arr = new List<int> { 3, 1, 2, 3 };          // Function call         Console.WriteLine(MinLength(n, k, arr));     } } 
JavaScript
//JavaScript code function minLength(n, k, arr) {     const f = new Map();      let cnt = 0;     for (let i = 0; i < n; i++) {         if (!f.has(arr[i])) {             f.set(arr[i], 1);         } else {             f.set(arr[i], f.get(arr[i]) + 1);             if (f.get(arr[i]) > k) {                 cnt++;             }         }     }      let l = 0, r = n;     let ans = n;      while (l <= r) {         const mid = l + Math.floor((r - l) / 2);         for (let i = 0; i < mid; i++) {             if (f.get(arr[i]) > k) {                 cnt--;             }             f.set(arr[i], f.get(arr[i]) - 1);         }         if (cnt === 0) {             ans = Math.min(ans, mid);             r = mid - 1;             for (let i = 0; i < mid; i++) {                 f.set(arr[i], f.get(arr[i]) + 1);                 if (f.get(arr[i]) > k) {                     cnt++;                 }             }             continue;         }         let flag = false;         for (let i = mid; i < n; i++) {             if (f.get(arr[i - mid]) >= k) {                 cnt++;             }             f.set(arr[i - mid], f.get(arr[i - mid]) + 1);                          if (f.get(arr[i]) > k) {                 cnt--;             }             f.set(arr[i], f.get(arr[i]) - 1);              if (cnt === 0) {                 for (let j = i - mid + 1; j <= i; j++) {                     f.set(arr[j], f.get(arr[j]) + 1);                     if (f.get(arr[j]) > k) {                         cnt++;                     }                 }                 flag = true;                 break;             }         }         if (flag) {             ans = Math.min(ans, mid);             r = mid - 1;         } else {             l = mid + 1;             for (let i = n - mid; i < n; i++) {                 f.set(arr[i], f.get(arr[i]) + 1);                 if (f.get(arr[i]) > k) {                     cnt++;                 }             }         }     }     return ans; }  // Driver code const n = 4; const k = 1; const arr = [3, 1, 2, 3];  // Function call console.log(minLength(n, k, arr)); //Contributed by Aditi Tyagi 

Output
1

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


Next Article
Maximize minimum sweetness in cake cutting

I

ishankhandelwals
Improve
Article Tags :
  • Searching
  • Hash
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Hash
  • Searching

Similar Reads

    Binary Search on Answer Tutorial with Problems
    Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and
    15+ min read
    Time Crunch Challenge
    Geeks for Geeks is organizing a hackathon consisting of N sections, each containing K questions. The duration of the hackathon is H hours. Each participant can determine their speed of solving questions, denoted as S (S = questions-per-hour). During each hour, a participant can choose a section and
    10 min read
    Find minimum subarray length to reduce frequency
    Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k. Examples: Input: n = 4, arr[] = {3, 1, 3, 6}, k =
    10 min read
    Maximize minimum sweetness in cake cutting
    Given that cake consists of N chunks, whose individual sweetness is represented by the sweetness[] array, the task is to cut the cake into K + 1 pieces to maximize the minimum sweetness. Examples: Input: N = 6, K = 2, sweetness[] = {6, 3, 2, 8, 7, 5}Output: 9Explanation: Divide the cake into [6, 3],
    7 min read
    Maximize minimum element of an Array using operations
    Given an array A[] of N integers and two integers X and Y (X ≤ Y), the task is to find the maximum possible value of the minimum element in an array A[] of N integers by adding X to one element and subtracting Y from another element any number of times, where X ≤ Y. Examples: Input: N= 3, A[] = {1,
    8 min read
    Maximize the minimum element and return it
    Given an array A[] of size N along with W, K. We can increase W continuous elements by 1 where we are allowed to perform this operation K times, the task is to maximize the minimum element and return the minimum element after operations. Examples: Input: N = 6, K = 2, W = 3, A[] = {2, 2, 2, 2, 1, 1}
    8 min read
    Find the maximum value of the K-th smallest usage value in Array
    Given an array arr[] of size N and with integers M, K. You are allowed to perform an operation where you can increase the value of the least element of the array by 1. You are to do this M times. The task is to find the largest possible value for the Kth smallest value among arr[] after M operations
    7 min read
    Aggressive Cows
    Given an array stalls[] which denotes the position of a stall and an integer k which denotes the number of aggressive cows. The task is to assign stalls to k cows such that the minimum distance between any two of them is the maximum possible.Examples: Input: stalls[] = [1, 2, 4, 8, 9], k = 3Output:
    15+ min read
    Minimum time to complete at least K tasks when everyone rest after each task
    Given an array arr[] of size n representing the time taken by a person to complete a task. Also, an array restTime[] which denotes the amount of time one person takes to rest after finishing a task. Each person is independent of others i.e. they can work simultaneously on different tasks at the same
    8 min read
    Maximum count of integers to be chosen from given two stacks having sum at most K
    Given two stacks stack1[] and stack2[] of size N and M respectively and an integer K, The task is to count the maximum number of integers from two stacks having sum less than or equal to K. Examples: Input: stack1[ ] = { 60, 90, 120 }stack2[ ] = { 100, 10, 10, 250 }, K = 130Output: 3Explanation: Tak
    9 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