
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to check if array pairs are divisible by k or not using Python
Suppose we have an array called nums, this array contains even number of elements, and have another value k. We have to split nums into exactly n/2 pairs such that the sum of each pair is divisible by k. If we can do so then return true, otherwise false.
So, if the input is like nums = [9,5,3,4,7,10,20,8] k = 3, then the output will be True because we can make pairs like (9,3), (5,7), (4,20), (8,10), sum of all pairs are divisible by 3.
To solve this, we will follow these steps −
dp := a new list
count:= 0
for each x in nums, do
t:= k - (x mod k)
if t is same as k, then
count := count + 1
otherwise,
insert t at the end of dp
if count mod 2 is not same as 0, then
return False
sort the list dp
low := 0
high := size of dp - 1
while low < high, do
if dp[low] + dp[high] is not same as k, then
return False
low := low + 1
high := high - 1
return True
Let us see the following implementation to get better understanding −
Example
def solve(nums, k): dp=[] count=0 for x in nums: t=k-(x % k) if t == k: count+=1 else: dp.append(t) if count % 2 != 0: return False dp.sort() low = 0 high = len(dp)-1 while low < high: if dp[low] + dp[high] != k: return False low += 1 high -= 1 return True nums = [9,5,3,4,7,10,20,8] k = 3 print(solve(nums, k))
Input
[9,5,3,4,7,10,20,8], 3
Output
True
- Related Articles
- Check if an array can be divided into pairs whose sum is divisible by k in Python
- Check if LCM of array elements is divisible by a prime number or not in Python
- Check if any large number is divisible by 17 or not in Python
- Check if any large number is divisible by 19 or not in Python
- Check if the Decimal representation of the given Binary String is divisible by K or not
- C Program to check if an array is palindrome or not using Recursion
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Program to check whether we can convert string in K moves or not using Python
- Count pairs in array whose sum is divisible by K in C++
- Check if a number is divisible by 23 or not in C++
- Check if a number is divisible by 41 or not in C++
- Program to check string is palindrome or not with equivalent pairs in Python
- Program to check if an Array is Palindrome or not using STL in C++
- Check if a large number is divisible by 11 or not in java
- Check if a large number is divisible by 3 or not in java
