Open In App

Minimum elements to be inserted such that no Subarray has sum 0

Last Updated : 30 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers such that no element is 0 in that array, the task is to find the minimum number of elements to be inserted such that no subarray of the new array has sum 0.

Examples:

Input: N = 3, arr[] = {1, -1, 1}
Output: 2
Explanation: As in the array the sum of first two element is 0 that is 1+(-1) =  0. 
To avoid this, insert an element. Insert 10 at position 2. 
The array become {1, 10, -1, 1}. 
Now the sum of last 2 element is 0. To avoid this insert an element. 
Insert 10 at position 4. Array become {1, 10, -1, 10, 1}. 
Now, no subarray have sum 0. 
So we have to insert minimum 2 integers in the array.

Input: N = 4, arr[] = {-2, 1, 2, 3}
Output: 
Explanation: No array is there whose sum is 0. 
So no need to insert element.

Approach: The problem can be solved based on the following observation.

Observations:

  • If we get any subarray with sum 0. Then insert an element just 1 place before the position where you got sum 0. So that sum will not remain 0 and start doing sum again.
  • Do the same process till the end and print how many times you have inserted element.

Follow the steps to solve the problem:

  • Take an unordered_map to store the sum detail to know if there is a subarray with sum 0.
  • Take a variable ans and initialize it to 0 to store the minimum number of elements to be inserted.
  • Traverse the array and add every element into the array and also note the sum detail in the map.
  • If, you got sum 0 (which can be found by checking if the sum is already present in the map): 
    • Then increase the ans by 1 and change the sum to the current element value because you have taken care of the previous elements and also remove the entries of the sum from the map.
    • Repeat this step whenever there is a subarray with sum 0.
  • In last return ans.

Below is the implementation for the above approach.

C++




// C++ code for the above approach:
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum count
// of required insertions
int getElements(int N, int arr[])
{
    // To store the previous sums
    unordered_map<long long int, int> forSum;
 
    // Final answer
    int ans = 0;
 
    // To store current sum
    long long int sum = 0;
 
    // Traversing array
    for (int i = 0; i < N; i++) {
 
        // Adding elements
        sum += arr[i];
 
        // Storing occurrence
        forSum[sum]++;
 
        // If found any subarray with sum 0
        if (sum == 0 || forSum[sum] > 1) {
            ans++;
 
            // New sum
            sum = arr[i];
 
            // Clearing previous data
            forSum.clear();
 
            // Storing new sum
            forSum[sum]++;
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int N = 3;
    int arr[] = { 1, -1, 1 };
 
    // Function call
    cout << getElements(N, arr) << endl;
    return 0;
}


Java




// Java code for the above approach:
import java.io.*;
import java.util.*;
 
class GFG
{
 
  // Function to find the minimum count
  // of required insertions
  public static int getElements(int N, int arr[])
  {
 
    // To store the previous sums
    HashMap<Integer, Integer> forSum
      = new HashMap<Integer, Integer>();
    // Final answer
    int ans = 0;
 
    // To store current sum
    int sum = 0;
 
    // Traversing array
    for (int i = 0; i < N; i++) {
 
      // Adding elements
      sum += arr[i];
 
      // Storing occurrence
      if (forSum.get(sum) != null)
        forSum.put(sum, forSum.get(sum) + 1);
      else
        forSum.put(sum, 1);
 
      // If found any subarray with sum 0
      if (sum == 0
          || (forSum.get(sum) != null
              && forSum.get(sum) > 1)) {
        ans++;
 
        // New sum
        sum = arr[i];
 
        // Clearing previous data
        forSum.clear();
 
        // Storing new sum
        forSum.put(sum, 1);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int N = 3;
    int arr[] = { 1, -1, 1 };
 
    // Function call
    System.out.print(getElements(N, arr));
  }
}
 
// This code is contributed by Rohit Pradhan


Python3




# Python code for the above approach
 
# Function to find the minimum count
# of required insertions
def getElements(N, arr):
   
    # To store the previous sums
    forSum = {}
 
    # Final answer
    ans = 0;
 
    # To store current sum
    sum = 0;
 
    # Traversing array
    for i in range(N):
 
        # Adding elements
        sum += arr[i];
 
        # Storing occurrence
        if(sum in forSum):
            forSum[sum] += 1
        else:
            forSum[sum] = 1
 
        # If found any subarray with sum 0
        if (sum == 0 or forSum[sum] > 1):
            ans += 1
 
            # New sum
            sum = arr[i];
 
            # Clearing previous data
            forSum.clear();
 
            # Storing new sum
            if(sum in forSum):
                forSum[sum] += 1
            else:
                forSum[sum] = 1
 
    return ans;
 
# Driver Code
N = 3;
arr = [ 1, -1, 1 ];
 
# Function call
print(getElements(N, arr));
         
# This code is contributed by Saurabh Jaiswal


C#




// C# implementation of above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  // Function to find the minimum count
  // of required insertions
  static int getElements(int N, int[] arr)
  {
 
    // To store the previous sums
    Dictionary<int,
    int> forSum = new Dictionary<int,int>();
 
    // Final answer
    int ans = 0;
 
    // To store current sum
    int sum = 0;
 
    // Traversing array
    for (int i = 0; i < N; i++) {
 
      // Adding elements
      sum += arr[i];
 
      // Storing occurrence
      forSum.Add(sum, 1);
 
      // If found any subarray with sum 0
      if (sum == 0 || forSum[sum] > 1) {
        ans++;
 
        // New sum
        sum = arr[i];
 
        // Clearing previous data
        forSum.Clear();
 
        // Storing new sum
        forSum.Add(sum, 1);
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 3;
    int[] arr = { 1, -1, 1 };
 
    // Function call
    Console.Write(getElements(N, arr));
  }
}
 
// This code is contributed by code_hunt.


Javascript




<script>
        // JavaScript code for the above approach
 
// Function to find the minimum count
// of required insertions
function getElements(N, arr)
{
    // To store the previous sums
    var forSum = new Map();
   //let  forSum= new Array();
 
    // Final answer
    let ans = 0;
 
    // To store current sum
    let sum = 0;
 
    // Traversing array
    for (let i = 0; i < N; i++) {
 
        // Adding elements
        sum += arr[i];
 
        // Storing occurrence
        forSum[sum]++;
 
        // If found any subarray with sum 0
        if (sum == 0 || forSum[sum] > 1) {
            ans++;
 
            // New sum
            sum = arr[i];
 
            // Clearing previous data
            forSum.clear();
 
            // Storing new sum
            forSum[sum]++;
        }
    }
    return ans;
}
 
        // Driver Code
 
    let N = 3;
    let arr = [ 1, -1, 1 ];
 
    // Function call
    document.write(getElements(N, arr));
         
        // This code is contributed by sanjoy_62.
    </script>


Output

2

Time Complexity: O(N) because the array is traversed only once and at most N elements are cleared from the map.
Auxiliary Space: O(N)



Similar Reads

Minimum count of elements to be inserted in Array to form all values in [1, K] using subset sum
Given a sorted array arr[] consisting of N integers, and an integer K, the task is to find the minimum number of elements to be inserted in the array such that any value in the range [1, K] can be formed by adding elements of any subset of the modified array. Examples: Input: arr[] = {1, 3}, K = 6Output: 1Explanation:Adding the number 2 to the arra
7 min read
Minimum characters that are to be inserted such that no three consecutive characters are same
Given a string str and the task is to modify the string such that no three consecutive characters are the same. In a single operation, any character can be inserted at any position in the string. Find the minimum number of such operations required. Examples: Input : str = "aabbbcc" Output: 1 Explanation: "aabbdbcc" is the modified string. Input: st
5 min read
Minimum 0s to be inserted in Array such that no element is same as its index
Given an array A = [A0, A1, A2, . . ., AN-1]. Perform the following operation: Total count of indices with value same as their positions.At each step, insert 0 at one of such positions.Repeat till no more elements exist whose value is same as the index. The task is to find the minimum number of insertions required such that no element is same as it
6 min read
Minimum elements to be inserted in Array to make adjacent differences equal
Given an array of integers Arr[]. The elements of the array are sorted in increasing order. The task is to find the minimum number of elements to be inserted in the array so that the differences between any two consecutive elements are the same. Examples: Input: Arr[] = {1, 4, 13, 19, 25} Output: 4 Explanation: One possible solution is: Arr[] = { 1
8 min read
Minimum elements inserted in a sorted array to form an Arithmetic progression
Given a sorted array arr[], the task is to find minimum elements needed to be inserted in the array such that array forms an Arithmetic Progression.Examples: Input: arr[] = {1, 6, 8, 10, 14, 16} Output: 10 Explanation: Minimum elements required to form A.P. is 10. Transformed array after insertion of the elements. arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9
8 min read
Count of elements to be inserted to make Array sum twice the XOR of Array
Given an array arr[] of size N, the task is to find the minimum number of elements that need to be inserted into the array so that the sum of the array is equal to two times the XOR of the array. Examples: Input: arr[] = {1, 2, 3, 6} Output: 0 Explanation: Xor = (1 ^ 2 ^ 3 ^ 6) = 6 and sum of the array = 12. The required condition (sum = 2 * Xor) s
8 min read
Number of positions where a letter can be inserted such that a string becomes palindrome
Given a string str, we need to find the no. of positions where a letter(lowercase) can be inserted so that string becomes a palindrome. Examples: Input : str = "abca" Output : possible palindromic strings: 1) acbca (at position 2) 2) abcba (at position 4) Hence, the output is 2. Input : str = "aaa" Output : possible palindromic strings: 1) aaaa 2)
11 min read
Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
Given two numbers x, y which denotes the number of set bits. Also given is a number C. The task is to print the number of ways in which we can form two numbers A and B such that A has x number of set bits and B has y number of set bits and A+B = C.Examples: Input: X = 1, Y = 1, C = 3 Output: 2 So two possible ways are (A = 2 and B = 1) and (A = 1 a
30 min read
Check if it is possible to create a matrix such that every row has A 1s and every column has B 1s
Given four integers N, M, A, B where N is the number of rows and M is the number of columns, the task is to check if is possible to create a binary matrix of dimensions N x M such that every row has A number of 1s and every column has a B number of 1s. If any such matrix is possible then print it else print "-1". Examples: Input: N = 3, M = 6, A =
14 min read
Minimum cost to convert all elements of a K-size subarray to 0 from given Ternary Array with subarray sum as cost
Given an array arr[] of N integers, where each array element is either 0, 1, or 2, and an integer K, the task is to print the minimum cost needed to convert all the elements of the array to 0s by selecting a subarray of size K and converting any array element of the subarray to 0 in one operation with the cost equal to the sum of elements of the su
11 min read
Article Tags :
Practice Tags :