08. Fraction pairs with sum 1
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To solve this problem, we can follow these steps:
Create a map to store simplified rational numbers, where the key is a pair
representing the numerator and denominator, and the value is the count of occurrences.
For each input fraction (num[i], den[i])
, calculate the greatest common divisor (GCD) of num[i]
and den[i]
using __gcd()
function, and then insert the simplified fraction into the map after dividing numerator and denominator by gcd.
Iterate through the map, and for each entry (nume, deno) -> cnt
:
If cnt
is not zero, calculate the new numerator newNume = deno - nume
we find this required numerator in our map since by adding this numerator we can easily make your pair sum = 1.
If nume
is equal to newNume
, add (cnt * (cnt - 1)) / 2
to the final result to count pairs that sum up to 1.
Otherwise, if (newNume, deno)
exists in the map, add cnt * mp[{newNume, deno}]
to the result and set mp[{newNume, deno}]
to zero.
Time Complexity : If n
is the number of fractions, the insertion and iteration take O(n log n)
time due to the map operations.
Auxiliary Space Complexity : O(n)
due to the space required for the map to store simplified fractions.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.