Check If Array Pairs Are Divisible by k

Updated on 20 May, 2025
Check If Array Pairs Are Divisible by k header image

Problem Statement

In this problem, we are given an array of integers arr with an even length n and an integer k. Our goal is to determine if it’s possible to split the array arr into n / 2 pairs such that the sum of each pair is divisible by k. If such a division is possible, the function should return true, otherwise it should return false. This requires checking combinations of elements in arr to find pairs that meet the divisibility criteria.

Examples

Example 1

Input:

arr = [1,2,3,4,5,10,6,7,8,9], k = 5

Output:

true

Explanation:

Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).

Example 2

Input:

arr = [1,2,3,4,5,6], k = 7

Output:

true

Explanation:

Pairs are (1,6),(2,5) and(3,4).

Example 3

Input:

arr = [1,2,3,4,5,6], k = 10

Output:

false

Explanation:

You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.

Constraints

  • arr.length == n
  • 1 <= n <= 105
  • n is even.
  • -109 <= arr[i] <= 109
  • 1 <= k <= 105

Approach and Intuition

  1. Remainder Utilization:
    Every integer leaves a remainder when divided by k. To make a pair where the sum is divisible by k, the sum of their remainders should either be 0 (if both are divisible by k) or k when added together. For example, a number with a remainder of 1 needs to be paired with a number with a remainder of k-1 for their sum to be divisible by k.

  2. Count Remainders:

    • First, we need to compute and count the remainders of each element in arr when divided by k.
    • A hashmap can be useful for counting occurrences of each remainder.
  3. Pair Formation Checks:

    • For each unique remainder, check if there's a complement remainder such that their summed pairs form a sum divisible by k.
    • Specifically, check if the count of elements that leave a remainder i is equal to the count of elements that leave the remainder k-i.
    • Special attention is required when i is 0 or if k/2 is also an integer (when k is even), because in such cases, we need an even number of such remainders to pair them among themselves.
  4. Return Value:
    If all remainder counts adequately pair up, return true. If any one type of remainder doesn't find its pair or has an incorrect count preventing it from pairing evenly, return false.

By following these logical steps, we can determine if pairing in the desired manner is possible. This method ensures that each pair consists of elements that together are divisible by k, aligning with the requirements outlined in the problem statement.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    struct ModComparator {
        int modValue;
        ModComparator(int mod) { modValue = mod; }
        bool operator()(int x, int y) {
            return (modValue + x % modValue) % modValue < (modValue + y % modValue) % modValue;
        }
    };

    bool canArrange(vector<int>& elements, int mod) {
        sort(elements.begin(), elements.end(), ModComparator(mod));

        int left = 0, right = elements.size() - 1;
        while (left < right) {
            if (elements[left] % mod != 0) break;
            if (elements[left + 1] % mod != 0) return false;
            left += 2;
        }

        while (left < right) {
            if ((elements[left] + elements[right]) % mod != 0) return false;
            left++;
            right--;
        }
        return true;
    }
};

The solution provided in C++ involves determining if the pairs in an array can be reorganized such that their sum is divisible by a given integer k. This is achieved by first sorting the elements of the array based on their modulo k results in a custom manner using a structure named ModComparator.

Explanation of the provided solution:

  1. Custom Sorting using ModComparator:

    • A custom comparator for sorting, ModComparator, reorders the array elements based on their modulo k results. This step groups numbers with equivalent remainders together, facilitating pair matching.
  2. Validity Check Using Two Pointers:

    • Utilizes two pointers, one starting at the first element (left) and the other at the last element (right), to check for pair validity:
      • It first checks if the mod result of the current leftmost element is zero. If not, the process breaks as the array won't possess the required pairing conditions.
      • Moves inwards checking the sum of the pairs (elements[left] + elements[right]) for modulo k divisibility.
      • Adjusts the pointers accordingly: left moves rightward, right moves leftward.
  3. Return Conditions:

    • If all pair checks pass (i.e., their sums are divisible by k until the pointers meet or cross), the function returns true.
    • If any pair does not meet the condition, the function immediately returns false, indicating that no valid reordering exists.

Through these steps, this algorithm effectively validates the divisibility by k for pairs formed from the array elements, making optimal use of sorting and iteration to verify pair conditions with a lesser computational load.

java
class Solution {
    
    // Class to compare integers by their modulo with k.
    private class ModComparator implements java.util.Comparator<Integer> {
        
        private int divisor;
        
        public ModComparator(int divisor) {
            this.divisor = divisor;
        }
        
        public int compare(Integer x, Integer y) {
            return ((divisor + (x % divisor)) % divisor) - ((divisor + (y % divisor)) % divisor);
        }
    }
    
    public boolean checkPairs(int[] numbers, int k) {
        Integer[] numArray = new Integer[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            numArray[i] = numbers[i];
        }

        Arrays.sort(numArray, new ModComparator(k));

        int left = 0, right = numArray.length - 1;
        while (left < right) {
            if (numArray[left] % k != 0) break;
            if (numArray[left + 1] % k != 0) return false;
            left += 2;
        }

        while (left < right) {
            if ((numArray[left] + numArray[right]) % k != 0) return false;
            left++;
            right--;
        }
        return true;
    }
}

The Java program provided is designed to solve the problem of checking if pairs of arrays are divisible by a given integer k. The solution utilizes the Comparator interface to sort an array based on modulo values, ensuring that elements with similar remainders when divided by k are grouped together. This is essential for efficiently pairing elements that meet the divisibility condition.

  • To begin, transform the input array of primitives into an Integer array.
  • Sort the Integer array using a custom comparator defined in the ModComparator class. This class sorts numbers based on their remainders when divided by k.
  • Once sorted, initialize two pointers: one starting at the beginning (left) and one at the end (right) of the array.
  • Check pairs from the start of the array to ensure that they are divisible by k. If a number at left is zero modulo k, ensure the next number is also zero modulo k, else the array cannot be paired completely as per the divisibility rule.
  • Shift the left pointer by two positions until the middle of the array is reached, continuously verifying the divisibility condition for pairs.
  • For the second half of the pairing process, move the left pointer towards the center from its current position, and the right pointer towards the center from the end. This action checks pairs formed by these pointers for divisibility by k.
  • Return true if all conditions are met for the entire array; otherwise, false.

By using the modulo comparator for sorting, this program reduces the complexity involved in directly checking each possible pair in the array, thus improving efficiency. The logical separation of pairs into those starting with elements divisible by k and others ensures that all scenarios are covered. With this approach, ensure that the array can indeed be completely paired up according to the divisibility condition set by k.

python
class Solution:
    def checkKDivisibilityPairs(self, numbers: List[int], divisor: int) -> bool:
        # Sort based on remainder of division by k after adjusting negative values
        numbers = sorted(numbers, key=lambda y: (divisor + y % divisor) % divisor)

        # Process pairs with zero remainders at the start
        left_index = 0
        right_index = len(numbers) - 1
        while left_index < right_index:
            if numbers[left_index] % divisor != 0:
                break
            if numbers[left_index + 1] % divisor != 0:
                return False
            left_index += 2

        # Process elements from opposite ends towards the middle
        while left_index < right_index:
            if (numbers[left_index] + numbers[right_index]) % divisor != 0:
                return False
            left_index += 1
            right_index -= 1

        return True

The Python snippet provided defines a class Solution with a method checkKDivisibilityPairs that checks if the pairs formed by the elements of an array numbers are divisible by a given integer divisor. The solution involves several key steps to ensure that pairs can be formed correctly:

  1. Sort the list numbers based on the remainder of the division by divisor, adjusted for negatives. This places elements that pair well next to each other.
  2. Initialize pointers for traversing the array from both ends towards the middle.
  3. Process elements with zero remainders first as these need to occur in pairs (i.e., even occurrences) to be divisible by divisor.
  4. Move to the main array processing; check pairs from opposite ends. Each pair's sum must be divisible by divisor to meet the criteria.
  5. Continue the check until all possible pairs are validated.

The function uses conditional checks and pointer increments to go through possible pairing scenarios efficiently, concluding with a boolean output that indicates whether the array meets the divisibility condition. Ensure the array's size and contents are appropriate for pairing before using this function in applications.

Comments

No comments yet.