Leetcode 1497: Check If Array Pairs Are Divisible by k

grid47
grid47
Exploring patterns and algorithms
Jun 10, 2024 5 min read

You are given an array of integers arr of even length n and an integer k. The task is to check if you can divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k. Return true if it’s possible to divide the array into valid pairs, otherwise return false.
Problem
Approach
Steps
Complexity
Input: The input consists of an array arr of even length n and an integer k.
Example: arr = [3, 1, 2, 6, 4, 10], k = 5
Constraints:
• 1 <= n <= 10^5
• n is even.
• -10^9 <= arr[i] <= 10^9
• 1 <= k <= 10^5
Output: Return true if it is possible to divide the array into valid pairs such that the sum of each pair is divisible by k. Otherwise, return false.
Example: Output: true
Constraints:
• The length of the array is even.
Goal: The goal is to check whether each element of the array can be paired with another element such that their sum is divisible by k.
Steps:
• Initialize an array to count the frequency of the remainders when dividing each element by k.
• For each element, compute its remainder when divided by k, and store this in the frequency array.
• Check if the frequency of elements with remainder 0 is even.
• For each non-zero remainder, check if the frequency of elements with remainder r is equal to the frequency of elements with remainder k-r.
Goal: The array has even length n, and k is a positive integer.
Steps:
• 1 <= n <= 10^5
• n is even.
• -10^9 <= arr[i] <= 10^9
• 1 <= k <= 10^5
Assumptions:
• The input array always has an even number of elements.
Input: arr = [3, 1, 2, 6, 4, 10], k = 5
Explanation: The valid pairs are (3, 7), (1, 9), (2, 8), and (4, 10), all of which sum to multiples of 5.

Input: arr = [1, 2, 3, 4, 5, 6], k = 10
Explanation: There are no valid pairs whose sum is divisible by 10.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus