| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.SpecialArray2; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class SpecialArray2PrefixSum : ISpecialArray2 |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(m + n) |
| | | 19 | | /// Space complexity - O(m) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <param name="queries"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public bool[] IsArraySpecial(int[] nums, int[][] queries) |
| | 2 | 25 | | { |
| | 2 | 26 | | var sameParity = new int[nums.Length - 1]; |
| | | 27 | | |
| | 18 | 28 | | for (var i = 0; i < nums.Length - 1; i++) |
| | 7 | 29 | | { |
| | 7 | 30 | | if (nums[i] % 2 == nums[i + 1] % 2) |
| | 2 | 31 | | { |
| | 2 | 32 | | sameParity[i] = 1; |
| | 2 | 33 | | } |
| | | 34 | | else |
| | 5 | 35 | | { |
| | 5 | 36 | | sameParity[i] = 0; |
| | 5 | 37 | | } |
| | 7 | 38 | | } |
| | | 39 | | |
| | 2 | 40 | | var prefixSum = new int[nums.Length]; |
| | | 41 | | |
| | 18 | 42 | | for (var i = 1; i < nums.Length; i++) |
| | 7 | 43 | | { |
| | 7 | 44 | | prefixSum[i] = prefixSum[i - 1]; |
| | | 45 | | |
| | 7 | 46 | | if (i - 1 < sameParity.Length) |
| | 7 | 47 | | { |
| | 7 | 48 | | prefixSum[i] += sameParity[i - 1]; |
| | 7 | 49 | | } |
| | 7 | 50 | | } |
| | | 51 | | |
| | 2 | 52 | | var result = new bool[queries.Length]; |
| | | 53 | | |
| | 10 | 54 | | for (var i = 0; i < queries.Length; i++) |
| | 3 | 55 | | { |
| | 3 | 56 | | var start = queries[i][0]; |
| | 3 | 57 | | var end = queries[i][1]; |
| | | 58 | | |
| | 3 | 59 | | var numBadPairs = prefixSum[end] - prefixSum[start]; |
| | | 60 | | |
| | 3 | 61 | | result[i] = numBadPairs == 0; |
| | 3 | 62 | | } |
| | | 63 | | |
| | 2 | 64 | | return result; |
| | 2 | 65 | | } |
| | | 66 | | } |