| | 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.CountOfInterestingSubarrays; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountOfInterestingSubarraysPrefixSum : ICountOfInterestingSubarrays |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(modulo) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="modulo"></param> |
| | 23 | | /// <param name="k"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public long CountInterestingSubarrays(IList<int> nums, int modulo, int k) |
| 3 | 26 | | { |
| 3 | 27 | | long result = 0; |
| | 28 | |
|
| 3 | 29 | | var prefixModDictionary = new Dictionary<int, int> |
| 3 | 30 | | { |
| 3 | 31 | | [0] = 1 |
| 3 | 32 | | }; |
| | 33 | |
|
| 3 | 34 | | var prefix = 0; |
| | 35 | |
|
| 31 | 36 | | foreach (var num in nums) |
| 11 | 37 | | { |
| 11 | 38 | | if (num % modulo == k) |
| 7 | 39 | | { |
| 7 | 40 | | prefix++; |
| 7 | 41 | | } |
| | 42 | |
|
| 11 | 43 | | var currentMod = prefix % modulo; |
| 11 | 44 | | var target = (currentMod - k + modulo) % modulo; |
| | 45 | |
|
| 11 | 46 | | if (prefixModDictionary.TryGetValue(target, out var count)) |
| 9 | 47 | | { |
| 9 | 48 | | result += count; |
| 9 | 49 | | } |
| | 50 | |
|
| 11 | 51 | | if (!prefixModDictionary.TryAdd(currentMod, 1)) |
| 5 | 52 | | { |
| 5 | 53 | | prefixModDictionary[currentMod]++; |
| 5 | 54 | | } |
| 11 | 55 | | } |
| | 56 | |
|
| 3 | 57 | | return result; |
| 3 | 58 | | } |
| | 59 | | } |