Here is an interesting programming puzzle I came across . Given an array of positive integers, and a number K. We need to find pairs(a,b) from the array such that a % b = K.
I have a naive O(n^2) solution to this where we can check for all pairs such that a%b=k. Works but inefficient. We can certainly do better than this can’t we ? Any efficient algorithms for the same? Oh and it’s NOT homework.
Sort your array and binary search or keep a hash table with the count of each value in your array.
For a number
x, we can find the largestysuch thatx mod y = Kasy = x - K. Binary search for thisyor look it up in your hash and increment your count accordingly.Now, this isn’t necessarily the only value that will work. For example,
8 mod 6 = 8 mod 3 = 2. We have:This means you will have to test all divisors of
yas well. You can find the divisors inO(sqrt y), giving you a total complexity ofO(n log n sqrt(max_value))if using binary search andO(n sqrt(max_value))with a hash table (recommended especially if your numbers aren’t very large).