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:
Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K
Next article icon

Length of smallest subarray to be removed to make sum of remaining elements divisible by K

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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[] = {3, 1, 4, 2}, K = 6
Output: 1
Explanation: Sum of array elements = 10, which is not divisible by 6. After removing the subarray {4}, sum of the remaining elements is 6. Therefore, the length of the removed subarray is 1.

Input: arr[] = {3, 6, 7, 1}, K = 9
Output: 2
Explanation: Sum of array elements = 17, which is not divisible by 9. After removing the subarray {7, 1} and the, sum of the remaining elements is 9. Therefore, the length of the removed subarray is 2.

Naive Approach: The simplest approach is to generate all possible subarray from the given array arr[] excluding the subarray of length N. Now, find the minimum length of subarray such that the difference between the sum of all the elements of the array and the sum of the elements in that subarray is divisible by K. If no such subarray exists, then print “-1”. 

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

Efficient Approach: To optimize the above approach, the idea is based on the below observation:

((total_sum – subarray_sum) % K + subarray_sum % K) must be equal to total_sum % K.
But, (total_sum – subarray_sum) % K == 0 should be true.

Therefore, total_sum % K == subarray_sum % K, so both subarray_sum and total_sum should leave the same remainder when divided by K. Hence, the task is to find the length of the smallest subarray whose sum of elements will leave a remainder of (total_sum % K).

Follow the steps below to solve this problem:

  • Initialize variable res as INT_MAX to store the minimum length of the subarray to be removed.
  • Calculate total_sum and the remainder which it leaves when divided by K.
  • Create an auxiliary array modArr[] to storing the remainder of each arr[i] when it is divided by K as:

modArr[i] = (arr[i] + K) % K.
where, 
K has been added while calculating the remainder to handle the case of negative integers.

  • Traverse the given array and maintain an unordered_map to stores the recent position of the remainder encountered and keep track of the minimum required subarray having the remainder same as the target_remainder.
  • If there exists any key in the map which is equal to (curr_remainder – target_remainder + K) % K, then store that subarray length in variable res as the minimum of res and current length found.
  • After the above, if res is unchanged the print “-1” Otherwise print the value of res.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
void removeSmallestSubarray(int arr[],
                            int n, int k)
{
    // Stores the remainder of each
    // arr[i] when divided by K
    int mod_arr[n];
  
    // Stores total sum of elements
    int total_sum = 0;
  
    // K has been added to each arr[i]
    // to handle -ve integers
    for (int i = 0; i < n; i++) {
        mod_arr[i] = (arr[i] + k) % k;
  
        // Update the total sum
        total_sum += arr[i];
    }
  
    // Remainder when total_sum
    // is divided by K
    int target_remainder
        = total_sum % k;
  
    // If given array is already
    // divisible by K
    if (target_remainder == 0) {
        cout << "0";
        return;
    }
  
    // Stores curr_remainder and the
    // most recent index at which
    // curr_remainder has occurred
    unordered_map<int, int> map1;
    map1[0] = -1;
  
    int curr_remainder = 0;
  
    // Stores required answer
    int res = INT_MAX;
  
    for (int i = 0; i < n; i++) {
  
        // Add current element to
        // curr_sum and take mod
        curr_remainder = (curr_remainder
                          + arr[i] + k)
                         % k;
  
        // Update current remainder index
        map1[curr_remainder] = i;
  
        int mod
            = (curr_remainder
               - target_remainder
               + k)
              % k;
  
        // If mod already exists in map
        // the subarray exists
        if (map1.find(mod) != map1.end())
            res = min(res, i - map1[mod]);
    }
  
    // If not possible
    if (res == INT_MAX || res == n) {
        res = -1;
    }
  
    // Print the result
    cout << res;
}
  
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 1, 4, 2 };
  
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Given K
    int K = 6;
  
    // Function Call
    removeSmallestSubarray(arr, N, K);
  
    return 0;
}
 
 

Java




// Java program for the
// above approach
import java.util.*;
class GFG{
  
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
static void removeSmallestSubarray(int arr[],
                                   int n, int k)
{
  // Stores the remainder of each
  // arr[i] when divided by K
  int []mod_arr = new int[n];
  
  // Stores total sum of
  // elements
  int total_sum = 0;
  
  // K has been added to each 
  // arr[i] to handle -ve integers
  for (int i = 0; i < n; i++) 
  {
    mod_arr[i] = (arr[i] + 
                  k) % k;
  
    // Update the total sum
    total_sum += arr[i];
  }
  
  // Remainder when total_sum
  // is divided by K
  int target_remainder = 
      total_sum % k;
  
  // If given array is already
  // divisible by K
  if (target_remainder == 0) 
  {
    System.out.print("0");
    return;
  }
  
  // Stores curr_remainder and the
  // most recent index at which
  // curr_remainder has occurred
  HashMap<Integer,
          Integer> map1 = 
          new HashMap<>();
  map1.put(0, -1);
  
  int curr_remainder = 0;
  
  // Stores required answer
  int res = Integer.MAX_VALUE;
  
  for (int i = 0; i < n; i++) 
  {
    // Add current element to
    // curr_sum and take mod
    curr_remainder = (curr_remainder + 
                      arr[i] + k) % k;
  
    // Update current remainder 
    // index
    map1.put(curr_remainder, i);
  
    int mod = (curr_remainder - 
               target_remainder + 
               k) % k;
  
    // If mod already exists in 
    // map the subarray exists
    if (map1.containsKey(mod))
      res = Math.min(res, i - 
                     map1.get(mod));
  }
  
  // If not possible
  if (res == Integer.MAX_VALUE || 
      res == n) 
  {
    res = -1;
  }
  
  // Print the result
  System.out.print(res);
}
  
// Driver Code
public static void main(String[] args)
{
  // Given array arr[]
  int arr[] = {3, 1, 4, 2};
  
  // Size of array
  int N = arr.length;
  
  // Given K
  int K = 6;
  
  // Function Call
  removeSmallestSubarray(arr, N, K);
}
}
  
// This code is contributed by gauravrajput1
 
 

Python3




# Python3 program for the above approach
import sys
  
# Function to find the length of the
# smallest subarray to be removed such
# that sum of elements is divisible by K
def removeSmallestSubarray(arr, n, k):
      
    # Stores the remainder of each
    # arr[i] when divided by K
    mod_arr = [0] * n
   
    # Stores total sum of elements
    total_sum = 0
   
    # K has been added to each arr[i]
    # to handle -ve integers
    for i in range(n) :
        mod_arr[i] = (arr[i] + k) % k
   
        # Update the total sum
        total_sum += arr[i]
          
    # Remainder when total_sum
    # is divided by K
    target_remainder = total_sum % k
   
    # If given array is already
    # divisible by K
    if (target_remainder == 0):
        print("0")
        return
      
    # Stores curr_remainder and the
    # most recent index at which
    # curr_remainder has occurred
    map1 = {}
    map1[0] = -1
   
    curr_remainder = 0
   
    # Stores required answer
    res = sys.maxsize 
   
    for i in range(n):
          
        # Add current element to
        # curr_sum and take mod
        curr_remainder = (curr_remainder + 
                             arr[i] + k) % k
   
        # Update current remainder index
        map1[curr_remainder] = i
   
        mod = (curr_remainder - 
             target_remainder + k) % k
   
        # If mod already exists in map
        # the subarray exists
        if (mod in map1.keys()):
            res = min(res, i - map1[mod])
      
    # If not possible
    if (res == sys.maxsize or res == n):
        res = -1
      
    # Print the result
    print(res)
  
# Driver Code
  
# Given array arr[]
arr = [ 3, 1, 4, 2 ]
   
# Size of array
N = len(arr) 
   
# Given K
K = 6
   
# Function Call
removeSmallestSubarray(arr, N, K)
  
# This code is contributed by susmitakundugoaldanga
 
 

C#




// C# program for the
// above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
static void removeSmallestSubarray(int []arr,
                                   int n, int k)
{
    
  // Stores the remainder of each
  // arr[i] when divided by K
  int []mod_arr = new int[n];
  
  // Stores total sum of
  // elements
  int total_sum = 0;
  
  // K has been added to each 
  // arr[i] to handle -ve integers
  for(int i = 0; i < n; i++) 
  {
    mod_arr[i] = (arr[i] + k) % k;
  
    // Update the total sum
    total_sum += arr[i];
  }
  
  // Remainder when total_sum
  // is divided by K
  int target_remainder = total_sum % k;
  
  // If given array is already
  // divisible by K
  if (target_remainder == 0) 
  {
    Console.Write("0");
    return;
  }
  
  // Stores curr_remainder and the
  // most recent index at which
  // curr_remainder has occurred
  Dictionary<int,
             int> map1 = new Dictionary<int,
                                        int>();
    
  map1.Add(0, -1);
  
  int curr_remainder = 0;
  
  // Stores required answer
  int res = int.MaxValue;
  
  for(int i = 0; i < n; i++) 
  {
      
    // Add current element to
    // curr_sum and take mod
    curr_remainder = (curr_remainder + 
                      arr[i] + k) % k;
  
    // Update current remainder 
    // index
    map1[curr_remainder] = i;
  
    int mod = (curr_remainder - 
               target_remainder + 
               k) % k;
  
    // If mod already exists in 
    // map the subarray exists
    if (map1.ContainsKey(mod))
      res = Math.Min(res, i - 
                     map1[mod]);
  }
  
  // If not possible
  if (res == int.MaxValue || 
      res == n) 
  {
    res = -1;
  }
    
  // Print the result
  Console.Write(res);
}
  
// Driver Code
public static void Main(String[] args)
{
    
  // Given array []arr
  int []arr = { 3, 1, 4, 2 };
  
  // Size of array
  int N = arr.Length;
  
  // Given K
  int K = 6;
  
  // Function Call
  removeSmallestSubarray(arr, N, K);
}
}
  
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
  
// JavaScript program for the above approach
  
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
function removeSmallestSubarray(arr, n, k) {
    // Stores the remainder of each
    // arr[i] when divided by K
    let mod_arr = new Array(n);
  
    // Stores total sum of elements
    let total_sum = 0;
  
    // K has been added to each arr[i]
    // to handle -ve integers
    for (let i = 0; i < n; i++) {
        mod_arr[i] = (arr[i] + k) % k;
  
        // Update the total sum
        total_sum += arr[i];
    }
  
    // Remainder when total_sum
    // is divided by K
    let target_remainder
        = total_sum % k;
  
    // If given array is already
    // divisible by K
    if (target_remainder == 0) {
        document.write("0");
        return;
    }
  
    // Stores curr_remainder and the
    // most recent index at which
    // curr_remainder has occurred
    let map1 = new Map();
    map1.set(0, -1);
  
    let curr_remainder = 0;
  
    // Stores required answer
    let res = Number.MAX_SAFE_INTEGER;
  
    for (let i = 0; i < n; i++) {
  
        // Add current element to
        // curr_sum and take mod
        curr_remainder = (curr_remainder
            + arr[i] + k)
            % k;
  
        // Update current remainder index
        map1.set(curr_remainder, i);
  
        let mod
            = (curr_remainder
                - target_remainder
                + k)
            % k;
  
        // If mod already exists in map
        // the subarray exists
        if (map1.has(mod))
            res = Math.min(res, i - map1.get(mod));
    }
  
    // If not possible
    if (res == Number.MAX_SAFE_INTEGER || res == n) {
        res = -1;
    }
  
    // Print the result
    document.write(res);
}
  
// Driver Code
  
// Given array arr[]
let arr = [3, 1, 4, 2];
  
// Size of array
let N = arr.length;
  
// Given K
let K = 6;
  
// Function Call
removeSmallestSubarray(arr, N, K);
  
</script>
 
 
Output: 
1

 

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K

K

kingluffy17
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Searching
  • array-rearrange
  • cpp-unordered_map
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Hash
  • Searching

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
  • 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
  • Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K
    Given a 2D matrix mat[][] of size N * M and a positive integer K, the task is to find the area of the smallest rectangular submatrix that is required to be removed such that the sum of the remaining elements in the matrix is divisible by K. Examples: Input: mat[][] = { {6, 2, 6}, {3, 2, 8}, {2, 5, 3
    15+ min read
  • Length of the Smallest Subarray that must be removed in order to Maximise the GCD
    Given an array arr[] of N elements, the task is to find the length of the smallest subarray such that when this subarray is removed from the array, the GCD of the resultant array is maximum. Note: The resulting array should be non-empty.Examples: Input: N = 4, arr[] = {3, 6, 1, 2} Output: 2 Explanat
    7 min read
  • Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal
    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,
    10 min read
  • Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays
    Given an array arr[] consisting of N integers, the task is to print the indices of two array elements required to be removed such that the given array can be split into three subarrays of equal sum. If not possible to do so, then print "-1". Examples: Input: arr[] = {2, 5, 12, 7, 19, 4, 3}Output: 2
    15+ min read
  • Minimum number of elements to be removed such that the sum of the remaining elements is equal to k
    Given an array arr[] of integers and an integer k, the task is to find the minimum number of integers that need to be removed from the array such that the sum of the remaining elements is equal to k. If we cannot get the required sum the print -1.Examples: Input: arr[] = {1, 2, 3}, k = 3 Output: 1 E
    8 min read
  • Count subarrays such that remainder after dividing sum of elements by K gives count of elements
    Given an array arr[] of size N and an element K. The task is to find the number of sub-arrays of the given array such that the remainder when dividing the sum of its elements by K is equal to the number of elements in the subarray. Examples: Input: arr[] = {1, 4, 2, 3, 5}, K = 4 Output: 4 {1}, {1, 4
    9 min read
  • Longest subarray with elements divisible by k
    Suppose you are given an array. You have to find the length of the longest subarray such that each and every element of it is divisible by k.Examples: Input : arr[] = { 1, 7, 2, 6, 8, 100, 3, 6, 16}, k=2Output : 4 Input : arr[] = { 3, 11, 22, 32, 55, 100, 1, 5}, k=5Output : 2 Approach: Initialize tw
    4 min read
  • Length of smallest Subarray with at least one element repeated K times
    Given an array arr[] of length N and an integer K. The task is to find the minimum length of subarray such that at least one element of the subarray is repeated exactly K times in that subarray. If no such subarray exists, print -1. Examples: Input: arr[] = {1, 2, 1, 2, 1}, K = 2Output: 3Explanation
    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