Program to check if array pairs are divisible by k or not using Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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
raja
Published on 28-May-2021 12:22:46
Advertisements