| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.SubarraySumsDivisibleByK; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SubarraySumsDivisibleByKArray : ISubarraySumsDivisibleByK |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(k) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int SubarraysDivByK(int[] nums, int k) |
| 9 | 25 | | { |
| 9 | 26 | | var result = 0; |
| | 27 | |
|
| 9 | 28 | | var prefixMod = 0; |
| | 29 | |
|
| 9 | 30 | | var modGroups = new int[k]; |
| | 31 | |
|
| 9 | 32 | | modGroups[0] = 1; |
| | 33 | |
|
| 69 | 34 | | foreach (var num in nums) |
| 21 | 35 | | { |
| 21 | 36 | | prefixMod = (prefixMod + (num % k) + k) % k; |
| | 37 | |
|
| 21 | 38 | | result += modGroups[prefixMod]; |
| | 39 | |
|
| 21 | 40 | | modGroups[prefixMod]++; |
| 21 | 41 | | } |
| | 42 | |
|
| 9 | 43 | | return result; |
| 9 | 44 | | } |
| | 45 | | } |