r/csinterviewproblems • u/CashierHound • Oct 22 '16
Given a rational number X/Y, find the closest approximation using a set of possible numerators A and a set of possible denominators B
Example: Say you are given the fraction 237/535, find its closest approximation using A=[0, 1, 2, 3, 4, 5] and B=[0, 1, 2, 3]
Is there a solution better than O(|A||B|)?
2
Upvotes
1
u/coldsnapped Oct 22 '16
If we sort the arrays beforehand, and then try binary search to get the best match in an array for each element in the second array, the Big-O complexity might be something like m log m + n log n + Min ( m log n, n log m)
On further simplification, we might get x log x where x is Max (m, n)
Here m and n are the sizes of the arrays.
I'm typing this on my cell, so if something looks screwed, forgive me :)
1
u/Secondsemblance Oct 22 '16
Simplest solution, test all numbers in the list: