| | 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.CheckIfArrayPairsAreDivisibleByK; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CheckIfArrayPairsAreDivisibleByKTwoPointers : ICheckIfArrayPairsAreDivisibleByK |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(log n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="arr"></param> |
| | 22 | | /// <param name="k"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public bool CanArrange(int[] arr, int k) |
| 8 | 25 | | { |
| 8 | 26 | | Array.Sort(arr, new Comparator(k)); |
| | 27 | |
|
| 8 | 28 | | var left = 0; |
| 8 | 29 | | var right = arr.Length - 1; |
| | 30 | |
|
| 13 | 31 | | while (left < right) |
| 11 | 32 | | { |
| 11 | 33 | | if (arr[left] % k != 0) |
| 5 | 34 | | { |
| 5 | 35 | | break; |
| | 36 | | } |
| | 37 | |
|
| 6 | 38 | | if (arr[left + 1] % k != 0) |
| 1 | 39 | | { |
| 1 | 40 | | return false; |
| | 41 | | } |
| | 42 | |
|
| 5 | 43 | | left += 2; |
| 5 | 44 | | } |
| | 45 | |
|
| 19 | 46 | | while (left < right) |
| 13 | 47 | | { |
| 13 | 48 | | if ((arr[left] + arr[right]) % k != 0) |
| 1 | 49 | | { |
| 1 | 50 | | return false; |
| | 51 | | } |
| | 52 | |
|
| 12 | 53 | | left++; |
| 12 | 54 | | right--; |
| 12 | 55 | | } |
| | 56 | |
|
| 6 | 57 | | return true; |
| 8 | 58 | | } |
| | 59 | |
|
| 8 | 60 | | private class Comparator(int k) : IComparer<int> |
| | 61 | | { |
| | 62 | | public int Compare(int i, int j) |
| 64 | 63 | | { |
| 64 | 64 | | return ((k + (i % k)) % k) - ((k + (j % k)) % k); |
| 64 | 65 | | } |
| | 66 | | } |
| | 67 | | } |