logo

Contar subarreglos con suma divisible por K

Dada una matriz llegar[] y un numero entero k la tarea es contar todos los subarreglos cuya suma es divisible por k .

Ejemplos:

Aporte: arreglo[] = [4 5 0 -2 -3 1] k = 5
Producción: 7
Explicación: Hay 7 subarreglos cuya suma es divisible por 5: [4 5 0 -2 -3 1] [5] [5 0] [5 0 -2 -3] [0] [0 -2 -3] y [-2 -3].



Aporte: arreglo[] = [2 2 2 2 2 2] k = 2
Producción: 21
Explicación: Todas las sumas de subarreglos son divisibles por 2.

Aporte: arreglo[] = [-1 -3 2] k = 5
Producción:
Explicación: No existe ningún subarreglo cuya suma sea divisible por k.

Tabla de contenido

[Enfoque ingenuo] Iterando sobre todos los subarreglos

La idea es iterar sobre todos los subarreglos posibles mientras se mantiene el seguimiento de los suma del subarreglo módulo k . Para cualquier subarreglo, si el módulo sub del subarreglo k se vuelve 0, incremente el recuento en 1. Después de iterar sobre todos los subarreglos, devuelva el recuento como resultado.

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)); 

Producción
7

Complejidad del tiempo: O(n^2) ya que estamos iterando sobre todos los puntos iniciales y finales posibles de los subarreglos.
Espacio Auxiliar: O(1)

[Enfoque esperado] Uso del módulo de suma de prefijos k

La idea es utilizar Técnica de suma de prefijos junto con hash . Al observar con atención, podemos decir que si un subarreglo arr[i...j] tiene una suma divisible por k, entonces (prefijo suma[i] % k) será igual a (prefijo suma[j] % k). Por lo tanto, podemos iterar sobre arr[] mientras mantenemos un mapa hash o un diccionario para contar el número de (prefijo suma mod k). Para cada índice i, el número de subarreglos que terminan en i y cuya suma es divisible por k será igual al recuento de apariciones de (prefijo suma[i] mod k) antes de i.

Nota: El valor negativo de (prefijo suma mod k) debe manejarse por separado en lenguajes como C++ Java DO# y javascript mientras que en Pitón (prefijo suma mod k) es siempre un valor no negativo ya que toma el signo del divisor que es 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)); 

Producción
7

Complejidad del tiempo: O(n) ya que estamos iterando sobre la matriz solo una vez.
Espacio Auxiliar: O(min(n k)) como máximo k Las claves pueden estar presentes en el mapa hash o en el diccionario.


Crear cuestionario