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, 7, 5, 1}, K = 7
Output: 2
Explanation:Â
Removing arr[0] from arr[] modifies arr[] to { 7, 5, 1 }. Therefore, sum = 13Â
Removing arr[1] from arr[] modifies arr[] to { 6, 5, 1 }. Therefore, sum = 12Â
Removing arr[2] from arr[] modifies arr[] to { 6, 7, 1 }. Therefore, sum = 14Â
Since the sum (= 14) is divisible by K(= 7), the required output is the index 2.ÂInput: arr[ ] = {14, 7, 8, 2, 4}, K = 7
Output: 1
Naive Approach: The simplest approach to solve this problem is to traverse the array and calculate the sum by removing the current element from the array. If the obtained sum is divisible by K, then print the current index. Otherwise, insert the removed element into the array.Â
Time Complexity: O(N2)Â
Auxiliary Space: O(1)
Approach: The above approach can be optimized by precalculating the sum of the array. Finally, traverse the array and check if (sum – arr[i]) is divisible by K or not. If found to be true, then print the current index. Follow the steps below to solve the problem:
- Calculate the sum of the array and store it in a variable say, sum.
- Initialize two variables say, res and mini to store the index of the smallest element and the element such that removing the elements makes the sum divisible by K.
- Traverse the array, and check if (sum – arr[i]) is divisible by K or not. If found to be true, then check if arr[i] is less than mini or not. If found to be true, then update mini = arr[i] and res = i.
- Finally, print the res.
Below is the implementation of the above approach:
C++14
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find index of the smallest array element// required to be removed to make sum divisible by Kint findIndex(int arr[], int n, int K){Â
    // Stores sum of array elements    int sum = 0;Â
    // Stores index of the smallest element    // removed from the array to make sum    // divisible by K    int res = -1;Â
    // Stores the smallest element removed    // from the array to make sum divisible by K    int mini = 1e9;Â
    // Traverse the array, arr[]    for (int i = 0; i < n; i++) {Â
        // Update sum        sum += arr[i];    }Â
    // Traverse the array arr[]    for (int i = 0; i < n; i++) {Â
        // Calculate remaining sum        int temp = sum - arr[i];Â
        // If sum is divisible by K        if (temp % K == 0) {Â
            // If res ==-1 or mini is greater            // than arr[i]            if (res == -1 || mini > arr[i]) {Â
                // Update res and mini                res = i + 1;                mini = arr[i];            }        }    }Â
    return res;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 14, 7, 8, 2, 4 };Â Â Â Â int K = 7;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    cout << findIndex(arr, N, K);Â
    return 0;} |
Java
// Java program to implement// the above approachimport java.util.*;class GFG{Â
// Function to find index of the smallest array element// required to be removed to make sum divisible by Kstatic int findIndex(int arr[], int n, int K){Â
    // Stores sum of array elements    int sum = 0;Â
    // Stores index of the smallest element    // removed from the array to make sum    // divisible by K    int res = -1;Â
    // Stores the smallest element removed    // from the array to make sum divisible by K    int mini = (int) 1e9;Â
    // Traverse the array, arr[]    for (int i = 0; i < n; i++)    {Â
        // Update sum        sum += arr[i];    }Â
    // Traverse the array arr[]    for (int i = 0; i < n; i++)    {Â
        // Calculate remaining sum        int temp = sum - arr[i];Â
        // If sum is divisible by K        if (temp % K == 0)        {Â
            // If res ==-1 or mini is greater            // than arr[i]            if (res == -1 || mini > arr[i])            {Â
                // Update res and mini                res = i + 1;                mini = arr[i];            }        }    }    return res;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int arr[] = { 14, 7, 8, 2, 4 };Â Â Â Â int K = 7;Â Â Â Â int N = arr.length;Â Â Â Â System.out.print(findIndex(arr, N, K));}}Â
// This code is contributed by shikhasingrajput |
Python3
# Python3 program to implement# the above approachÂ
# Function to find index of the smallest array element# required to be removed to make sum divisible by Kdef findIndex(arr, n, K) :Â
    # Stores sum of array elements    sum = 0Â
    # Stores index of the smallest element    # removed from the array to make sum    # divisible by K    res = -1Â
    # Stores the smallest element removed    # from the array to make sum divisible by K    mini = 1e9Â
    # Traverse the array, arr[]    for i in range(n):Â
        # Update sum        sum += arr[i]Â
    # Traverse the array arr[]    for i in range(n):Â
        # Calculate remaining sum        temp = sum - arr[i]Â
        # If sum is divisible by K        if (temp % K == 0) :Â
            # If res ==-1 or mini is greater            # than arr[i]            if (res == -1 or mini > arr[i]) :Â
                # Update res and mini                res = i + 1                mini = arr[i]    return res;Â
# Driver Codearr = [ 14, 7, 8, 2, 4 ]K = 7N = len(arr)print(findIndex(arr, N, K))Â
# This code is contributed by sanjoy_62. |
C#
// C# program to implement // the above approach using System;Â
class GFG{     // Function to find index of the smallest// array element required to be removed // to make sum divisible by K static int findIndex(int[] arr, int n, int K) {          // Stores sum of array elements     int sum = 0;        // Stores index of the smallest    // element removed from the array    // to make sum divisible by K     int res = -1;        // Stores the smallest element     // removed from the array to     // make sum divisible by K     int mini = (int)1e9;        // Traverse the array, arr[]     for(int i = 0; i < n; i++)    {                  // Update sum         sum += arr[i];     }        // Traverse the array arr[]     for(int i = 0; i < n; i++)     {                  // Calculate remaining sum         int temp = sum - arr[i];            // If sum is divisible by K         if (temp % K == 0)        {                          // If res ==-1 or mini is greater             // than arr[i]             if (res == -1 || mini > arr[i])            {                                  // Update res and mini                 res = i + 1;                 mini = arr[i];             }         }     }     return res; } Â
// Driver code   static void Main() {    int[] arr = { 14, 7, 8, 2, 4 };     int K = 7;     int N = arr.Length;          Console.WriteLine(findIndex(arr, N, K)); }}Â
// This code is contributed by divyeshrabadiya07 |
Javascript
<script>Â
// JavaScript program to implement// the above approachÂ
// Function to find index of the smallest array element// required to be removed to make sum divisible by Kfunction findIndex(arr,n,K){Â
    // Stores sum of array elements    let sum = 0;Â
    // Stores index of the smallest element    // removed from the array to make sum    // divisible by K    let res = -1;Â
    // Stores the smallest element removed    // from the array to make sum divisible by K    let mini = parseInt( 1e9);Â
    // Traverse the array, arr[]    for (let i = 0; i < n; i++)    {Â
        // Update sum        sum += arr[i];    }Â
    // Traverse the array arr[]    for (let i = 0; i < n; i++)    {Â
        // Calculate remaining sum        let temp = sum - arr[i];Â
        // If sum is divisible by K        if (temp % K == 0)        {Â
            // If res ==-1 or mini is greater            // than arr[i]            if (res == -1 || mini > arr[i])            {Â
                // Update res and mini                res = i + 1;                mini = arr[i];            }        }    }    return res;}Â
// Driver CodeÂ
    let arr = [ 14, 7, 8, 2, 4 ];    let K = 7;    let N = arr.length;    document.write(findIndex(arr, N, K));Â
Â
// This code is contributed by sravan kumarÂ
</script> |
Â
Â
2
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



