| | 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 SubarraySumsDivisibleByKDictionary : 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 prefixModDictionary = new Dictionary<int, int> { { 0, 1 } }; |
| | 29 | |
|
| 9 | 30 | | var sum = 0; |
| | 31 | |
|
| 69 | 32 | | foreach (var num in nums) |
| 21 | 33 | | { |
| 21 | 34 | | sum += num; |
| | 35 | |
|
| 21 | 36 | | var prefixMod = sum % k; |
| | 37 | |
|
| 21 | 38 | | if (prefixMod < 0) |
| 0 | 39 | | { |
| 0 | 40 | | prefixMod += k; |
| 0 | 41 | | } |
| | 42 | |
|
| 21 | 43 | | if (prefixModDictionary.TryAdd(prefixMod, 1)) |
| 3 | 44 | | { |
| 3 | 45 | | continue; |
| | 46 | | } |
| | 47 | |
|
| 18 | 48 | | result += prefixModDictionary[prefixMod]; |
| | 49 | |
|
| 18 | 50 | | prefixModDictionary[prefixMod]++; |
| 18 | 51 | | } |
| | 52 | |
|
| 9 | 53 | | return result; |
| 9 | 54 | | } |
| | 55 | | } |