Minimum and Maximum of all subarrays of size K using Map
Given an array arr[] of N integers and an integer K, the task is to find the minimum and maximum of all subarrays of size K. Examples:
Input: arr[] = {2, -2, 3, -9, -5, -8}, K = 4 Output: -9 3 -9 3 -9 3 Explanation: Below are the subarray of size 4 and minimum and maximum value of each subarray: 1. {2, -2, 3, -9}, minValue = -9, maxValue = 3 2. {-2, 3, -9, -5}, minValue = -9, maxValue = 3 3. {3, -9, -5, -8}, minValue = -9, maxValue = 3 Input: arr[] = { 5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1 }, K = 3 Output: 3 5 2 4 1 3 1 6 1 6 3 6 3 5 2 5 1 4
Approach:
- Traverse the given array upto K elements and store the count of each element into a map.
- After inserting K elements, for each remaining elements do the following:
- Increase the frequency of current element arr[i] by 1.
- Decrease the frequency of arr[i – K + 1] by 1 to store the frequency of current subarray(arr[i – K + 1, i]) of size K.
- Since map stores the key value pair in sorted order. Therefore the iterator at the starting of the map stores the minimum element and at the ending of the map stores the maximum element. Print the minimum and maximum element of the current subarray.
- Repeat the above steps for each subarray formed.
Below is the implementation of the above approach:
CPP
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find the minimum and // maximum element for each subarray // of size K int maxSubarray( int arr[], int n, int k) { // To store the frequency of element // for every subarray map< int , int > Map; // To count the subarray array size // while traversing array int l = 0; // Traverse the array for ( int i = 0; i < n; i++) { // Increment till we store the // frequency of first K element l++; // Update the count for current // element Map[arr[i]]++; // If subarray size is K, then // find the minimum and maximum // for each subarray if (l == k) { // Iterator points to end // of the Map auto itMax = Map.end(); itMax--; // Iterator points to start of // the Map auto itMin = Map.begin(); // Print the minimum and maximum // element of current sub-array cout << itMin->first << ' ' << itMax->first << endl; // Decrement the frequency of // arr[i - K + 1] Map[arr[i - k + 1]]--; // if arr[i - K + 1] is zero // remove from the map if (Map[arr[i - k + 1]] == 0) { Map.erase(arr[i - k + 1]); } l--; } } return 0; } // Driver Code int main() { // Given array arr[] int arr[] = { 5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1 }; // Subarray size int k = 3; int n = sizeof (arr) / sizeof (arr[0]); // Function Call maxSubarray(arr, n, k); return 0; } |
Java
/*package whatever //do not write package name here */ import java.util.*; class GFG { // Function to find the minimum and // maximum element for each subarray // of size K static int maxSubarray( int arr[], int n, int k) { // To store the frequency of element // for every subarray TreeMap<Integer, Integer> Map = new TreeMap<>(); // To count the subarray array size // while traversing array int l = 0 ; // Traverse the array for ( int i = 0 ; i < n; i++) { // Increment till we store the // frequency of first K element l++; // Update the count for current // element Map.put(arr[i],Map.getOrDefault(arr[i], 0 )+ 1 ); // If subarray size is K, then // find the minimum and maximum // for each subarray if (l == k) { // Iterator points to end // of the Map var itMax = getLast(Map); // Iterator points to start of // the Map var itMin = getFirst(Map); // Print the minimum and maximum // element of current sub-array System.out.println(itMin.getKey() + " " + itMax.getKey()); // Decrement the frequency of // arr[i - K + 1] Map.put(arr[i - k + 1 ],Map.getOrDefault(arr[i - k + 1 ], 0 )- 1 ); // if arr[i - K + 1] is zero // remove from the map if (Map.get(arr[i - k + 1 ]) == 0 ) { Map.remove(arr[i - k + 1 ]); } l--; } } return 0 ; } static Map.Entry<Integer, Integer> getFirst(TreeMap<Integer, Integer> lhm){ int count = 1 ; for (Map.Entry<Integer, Integer> it : lhm.entrySet()) { if (count == 1 ) { return it; } count++; } return null ; } static Map.Entry<Integer, Integer> getLast(TreeMap<Integer, Integer> lhm) { int count = 1 ; for (Map.Entry<Integer, Integer> it : lhm.entrySet()) { if (count == lhm.size()) { return it; } count++; } return null ; } public static void main (String[] args) { // Given array arr[] int arr[] = { 5 , 4 , 3 , 2 , 1 , 6 , 3 , 5 , 4 , 2 , 1 }; // Subarray size int k = 3 ; int n = arr.length; // Function Call maxSubarray(arr, n, k); } } // This code is contributed by aadityaburujwale. |
Python3
# Function to find the minimum and # maximum element for each subarray # of size K def maxSubarray(arr, n, k): # To store the frequency of element # for every subarray map = dict () # To count the subarray array size # while traversing array l = 0 # Traverse the array for i in range (n): # Increment till we store the # frequency of first K element l + = 1 # Update the count for current # element if arr[i] in map : map [arr[i]] + = 1 else : map [arr[i]] = 1 # If subarray size is K, then # find the minimum and maximum # for each subarray if l = = k: # Iterator points to end # of the Map itMax = max ( map .keys()) # Iterator points to start of # the Map itMin = min ( map .keys()) # Print the minimum and maximum # element of current sub-array print (itMin, itMax) # Decrement the frequency of # arr[i - K + 1] map [arr[i - k + 1 ]] - = 1 # if arr[i - K + 1] is zero # remove from the map if map [arr[i - k + 1 ]] = = 0 : del map [arr[i - k + 1 ]] l - = 1 return 0 # Given array arr[] arr = [ 5 , 4 , 3 , 2 , 1 , 6 , 3 , 5 , 4 , 2 , 1 ] # Subarray size k = 3 n = len (arr) # Function Call maxSubarray(arr, n, k) # This code is contributed by akashish__ |
C#
using System; using System.Collections.Generic; class GFG { // Function to find the minimum and // maximum element for each subarray // of size K static int maxSubarray( int [] arr, int n, int k) { // To store the frequency of element // for every subarray SortedDictionary< int , int > Map = new SortedDictionary< int , int >(); // To count the subarray array size // while traversing array int l = 0; // Traverse the array for ( int i = 0; i < n; i++) { // Increment till we store the // frequency of first K element l++; // Update the count for current // element if (!Map.ContainsKey(arr[i])) { Map.Add(arr[i], 1); } else { Map[arr[i]]++; } // If subarray size is K, then // find the minimum and maximum // for each subarray if (l == k) { // Iterator points to end // of the Map var itMax = getLast(Map); // Iterator points to start of // the Map var itMin = getFirst(Map); // Print the minimum and maximum // element of current sub-array Console.WriteLine(itMin.Key + " " + itMax.Key); // Decrement the frequency of // arr[i - K + 1] Map[arr[i - k + 1]]--; // if arr[i - K + 1] is zero // remove from the map if (Map[arr[i - k + 1]] == 0) { Map.Remove(arr[i - k + 1]); } l--; } } return 0; } static KeyValuePair< int , int > getFirst(SortedDictionary< int , int > lhm) { int count = 1; foreach (KeyValuePair< int , int > it in lhm) { if (count == 1) { return it; } count++; } return default (KeyValuePair< int , int >); } static KeyValuePair< int , int > getLast(SortedDictionary< int , int > lhm) { int count = 1; foreach (KeyValuePair< int , int > it in lhm) { if (count == lhm.Count) { return it; } count++; } return default (KeyValuePair< int , int >); } public static void Main( string [] args) { // Given array arr[] int [] arr = { 5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1 }; // Subarray size int k = 3; int n = arr.Length; // Function Call maxSubarray(arr, n, k); } } // This code is contributed by akashish__ |
Javascript
// Function to find the minimum and // maximum element for each subarray // of size K function maxSubarray(arr, n, k) { // To store the frequency of element // for every subarray let map = new Map(); // To count the subarray array size // while traversing array let l = 0; // Traverse the array for (let i = 0; i < n; i++) { // Increment till we store the // frequency of first K element l++; // Update the count for current // element if (map.has(arr[i])) { map.set(arr[i], map.get(arr[i]) + 1); } else { map.set(arr[i], 1); } // If subarray size is K, then // find the minimum and maximum // for each subarray if (l === k) { // Iterator points to end // of the Map let itMax = map.keys().next().value; for (let key of map.keys()) { itMax = Math.max(itMax, key); } // Iterator points to start of // the Map let itMin = map.keys().next().value; for (let key of map.keys()) { itMin = Math.min(itMin, key); } // Print the minimum and maximum // element of current sub-array console.log(itMin + " " + itMax); // Decrement the frequency of // arr[i - K + 1] map.set(arr[i - k + 1], map.get(arr[i - k + 1]) - 1); // if arr[i - K + 1] is zero // remove from the map if (map.get(arr[i - k + 1]) === 0) { map. delete (arr[i - k + 1]); } l--; } } return 0; } // Given array arr[] let arr = [5, 4, 3, 2, 1, 6, 3, 5, 4, 2, 1]; // Subarray size let k = 3; let n = arr.length; // Function Call maxSubarray(arr, n, k); // This code is contributed by akashish__ |
Output:
3 5 2 4 1 3 1 6 1 6 3 6 3 5 2 5 1 4
Time Complexity: O(N*log K), where N is the number of element. Auxiliary Space: O(K), where K is the size of subarray.
Contact Us