logo

Contare sottoarray con somma divisibile per K

Dato un array arr[] e un numero intero k il compito è contare tutti i sottoarray la cui somma è divisibile per k .

Esempi:

Ingresso: arr[] = [4 5 0 -2 -3 1] k = 5
Produzione: 7
Spiegazione: Esistono 7 sottoarray la cui somma è divisibile per 5: [4 5 0 -2 -3 1] [5] [5 0] [5 0 -2 -3] [0] [0 -2 -3] e [-2 -3].



Ingresso: arr[] = [2 2 2 2 2 2] k = 2
Produzione: 21
Spiegazione: Tutte le somme dei sottoarray sono divisibili per 2.

Ingresso: arr[] = [-1 -3 2] k = 5
Produzione:
Spiegazione: Non esiste un sottoarray la cui somma sia divisibile per k.

Sommario

età del dharmendra

[Approccio ingenuo] Iterazione su tutti i sottoarray

L'idea è di scorrere tutti i possibili sottoarray mantenendo traccia del file somma del sottoarray modulo k . Per qualsiasi sottoarray se il sottoarray modulo k diventa 0, incrementare il conteggio di 1. Dopo aver ripetuto tutti i sottoarray, restituisce il conteggio come risultato.

C++
// C++ Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays #include    #include  using namespace std; int subCount(vector<int> &arr int k) {  int n = arr.size() res = 0;     // Iterating over starting indices of subarray  for(int i = 0; i < n; i++) {  int sum = 0;    // Iterating over ending indices of subarray  for(int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if(sum == 0)  res += 1;  }  }  return res; } int main() {  vector<int> arr = {4 5 0 -2 -3 1};  int k = 5;    cout << subCount(arr k); } 
C
// C Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays #include  int subCount(int arr[] int n int k) {  int res = 0;  // Iterating over starting indices of subarray  for (int i = 0; i < n; i++) {  int sum = 0;  // Iterating over ending indices of subarray  for (int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum == 0)  res += 1;  }  }  return res; } int main() {  int arr[] = {4 5 0 -2 -3 1};  int k = 5;  int n = sizeof(arr) / sizeof(arr[0]);  printf('%d' subCount(arr n k));  return 0; } 
Java
// Java Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays import java.util.*; class GfG {  static int subCount(int[] arr int k) {  int n = arr.length res = 0;  // Iterating over starting indices of subarray  for (int i = 0; i < n; i++) {  int sum = 0;  // Iterating over ending indices of subarray  for (int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum == 0)  res += 1;  }  }  return res;  }  public static void main(String[] args) {  int[] arr = {4 5 0 -2 -3 1};  int k = 5;  System.out.println(subCount(arr k));  } } 
Python
# Python Code to Count Subarrays With Sum Divisible By K # by iterating over all possible subarrays def subCount(arr k): n = len(arr) res = 0 # Iterating over starting indices of subarray for i in range(n): sum = 0 # Iterating over ending indices of subarray for j in range(i n): sum = (sum + arr[j]) % k if sum == 0: res += 1 return res if __name__ == '__main__': arr = [4 5 0 -2 -3 1] k = 5 print(subCount(arr k)) 
C#
// C# Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays using System; using System.Collections.Generic; class GfG {   static int subCount(int[] arr int k) {  int n = arr.Length res = 0;  // Iterating over starting indices of subarray  for (int i = 0; i < n; i++) {  int sum = 0;  // Iterating over ending indices of subarray  for (int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum == 0)  res += 1;  }  }  return res;  }  static void Main() {  int[] arr = { 4 5 0 -2 -3 1 };  int k = 5;  Console.WriteLine(subCount(arr k));  } } 
JavaScript
// JavaScript Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays function subCount(arr k) {  let n = arr.length res = 0;  // Iterating over starting indices of subarray  for (let i = 0; i < n; i++) {  let sum = 0;  // Iterating over ending indices of subarray  for (let j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum === 0)  res += 1;  }  }  return res; } // Driver Code let arr = [4 5 0 -2 -3 1]; let k = 5; console.log(subCount(arr k)); 

Produzione
7

Complessità temporale: O(n^2) poiché stiamo iterando su tutti i possibili punti iniziali e finali dei sottoarray.
Spazio ausiliario: O(1)

[Approccio previsto] Utilizzo della somma dei prefissi modulo k

L'idea è usare Tecnica della somma dei prefissi insieme a Hashing . Osservando attentamente possiamo dire che se un sottoarray arr[i...j] ha somma divisibile per k allora (prefisso sum[i] % k) sarà uguale a (prefisso sum[j] % k). Quindi possiamo scorrere su arr[] mantenendo una mappa hash o un dizionario per contare il numero di (prefisso sum mod k). Per ogni indice i il numero di sottoarray che terminano con i e aventi somma divisibile per k sarà uguale al conteggio delle occorrenze di (prefisso sum[i] mod k) prima di i.

Nota: Il valore negativo di (prefisso sum mod k) deve essere gestito separatamente in linguaggi come C++ Giava C# E JavaScript mentre in Pitone (prefisso somma mod k) è sempre un valore non negativo in quanto prende il segno del divisore cioè k .

C++
// C++ Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map #include    #include  #include  using namespace std; int subCount(vector<int> &arr int k) {  int n = arr.size() res = 0;  unordered_map<int int> prefCnt;  int sum = 0;    // Iterate over all ending points  for(int i = 0; i < n; i++) {    // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;    // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if(sum == 0)  res += 1;    // Add count of all starting points for index i  res += prefCnt[sum];    prefCnt[sum] += 1;  }  return res; } int main() {  vector<int> arr = {4 5 0 -2 -3 1};  int k = 5;    cout << subCount(arr k); } 
Java
// Java Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map import java.util.*; class GfG {  static int subCount(int[] arr int k) {  int n = arr.length res = 0;  Map<Integer Integer> prefCnt = new HashMap<>();  int sum = 0;  // Iterate over all ending points  for (int i = 0; i < n; i++) {  // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;  // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if (sum == 0)  res += 1;  // Add count of all starting points for index i  res += prefCnt.getOrDefault(sum 0);  prefCnt.put(sum prefCnt.getOrDefault(sum 0) + 1);  }  return res;  }  public static void main(String[] args) {  int[] arr = {4 5 0 -2 -3 1};  int k = 5;  System.out.println(subCount(arr k));  } } 
Python
# Python Code to Count Subarrays With Sum Divisible By K # using Prefix Sum and Dictionary from collections import defaultdict def subCount(arr k): n = len(arr) res = 0 prefCnt = defaultdict(int) sum = 0 # Iterate over all ending points for i in range(n): sum = (sum + arr[i]) % k # If sum == 0 then increment the result by 1 # to count subarray arr[0...i] if sum == 0: res += 1 # Add count of all starting points for index i res += prefCnt[sum] prefCnt[sum] += 1 return res if __name__ == '__main__': arr = [4 5 0 -2 -3 1] k = 5 print(subCount(arr k)) 
C#
// C# Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map using System; using System.Collections.Generic; class GfG {  static int SubCount(int[] arr int k) {  int n = arr.Length res = 0;  Dictionary<int int> prefCnt = new Dictionary<int int>();  int sum = 0;  // Iterate over all ending points  for (int i = 0; i < n; i++) {    // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;  // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if (sum == 0)  res += 1;  // Add count of all starting points for index i  if (prefCnt.ContainsKey(sum))  res += prefCnt[sum];  if (prefCnt.ContainsKey(sum))  prefCnt[sum] += 1;  else  prefCnt[sum] = 1;  }  return res;  }  static void Main() {  int[] arr = { 4 5 0 -2 -3 1 };  int k = 5;  Console.WriteLine(SubCount(arr k));  } } 
JavaScript
// JavaScript Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map function subCount(arr k) {  let n = arr.length res = 0;  let prefCnt = new Map();  let sum = 0;  // Iterate over all ending points  for (let i = 0; i < n; i++) {  // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;  // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if (sum === 0)  res += 1;  // Add count of all starting points for index i  res += (prefCnt.get(sum) || 0);  prefCnt.set(sum (prefCnt.get(sum) || 0) + 1);  }  return res; } // Driver Code let arr = [4 5 0 -2 -3 1]; let k = 5; console.log(subCount(arr k)); 

Produzione
7

Complessità temporale: O(n) poiché stiamo iterando sull'array solo una volta.
Spazio ausiliario: O(min(nk)) come al massimo k le chiavi possono essere presenti nella mappa hash o nel dizionario.


Crea quiz