Check pairs divisible by K - PrismoSkills
Problem: Given an array having even number of integers. Find if the array has N / 2 pairs of integers such that each pair is divisible by a given number k. Example: A normal approach would be to try all the pairs possible and see if the array holds the above property. However, that would be a very costly approach in terms of efficiency and an O(n) solution is possible for this problem. Code: public class CheckPairDivisibility { public static void main(String[] args) { boolean isPairs = checkPairs (new int []{12, 30, 20, 22}, 6); System.out.println(isPairs); } static boolean checkPairs(int nums[], int k) { // Debug prints System.out.println("k = " + k); printArray (nums, "input "); // initialize counts of modulus int modulusCounts[] = new int[k]; for(int i = 0; i < k; i++) modulusCounts[i] = 0; // For each number in the array, calculate // modulus and update relevant count for (int num: nums) modulusCounts[num %k]++; if (modulusCounts[0] % 2 !Read full article from Check pairs divisible by K - PrismoSkills