Magicsheet logo

Equal Rational Numbers

Hard
12.5%
Updated 8/1/2025

Asked by 2 Companies

Equal Rational Numbers

What is this problem about?

The Equal Rational Numbers coding problem asks you to determine if two given strings representing rational numbers are equal. The strings can be in three formats: integer ("15"), finite decimal ("15.75"), or repeating decimal ("15.7(5)" where the part in parentheses repeats infinitely). You need to handle cases like "0.9(9)" being equal to "1".

Why is this asked in interviews?

Companies like Microsoft and Google ask the Equal Rational Numbers interview question to test a candidate's mathematical accuracy and string parsing skills. It evaluates how you handle infinite sequences and whether you can convert complex string representations into a standard format, such as a simplified fraction (numerator and denominator), for comparison.

Algorithmic pattern used

The most robust approach is Fraction Conversion (Rational Math).

  1. Parse the string into three parts: integer, non-repeating decimal, and repeating decimal.
  2. Convert the finite part to a fraction: integer + decimal / 10^k.
  3. Convert the repeating part to a fraction using the formula: repeating_unit / (10^len - 1) * 10^-offset.
  4. Add the fractions and simplify using the Greatest Common Divisor (GCD).
  5. Compare the simplified (numerator, denominator) pairs of both numbers.

Example explanation

Suppose we compare 0.1(6) and 1/6.

  1. 0.1(6) has integer 0, finite 0.1, and repeating 0.0(6).
  2. Finite part: 1/10.
  3. Repeating part: 6 / 9 (because 6 repeats) shifted by 1 decimal place = 6 / 90 = 1/15.
  4. Total: 1/10 + 1/15 = 3/30 + 2/30 = 5/30.
  5. Simplify 5/30: 1/6.
  6. Both are equal.

Common mistakes candidates make

  • Float Precision: Using double or float types, which cannot represent repeating decimals accurately and will lead to rounding errors.
  • Ignoring 0.9(9) case: Not correctly handling the edge case where a repeating 9 increases the previous digit.
  • Complex Regex: Getting bogged down in complex string splitting instead of a clean, step-by-step parse.

Interview preparation tip

Whenever you need to compare numbers that can have infinite precision or repeating patterns, always use fractions (numerator/denominator). It’s the only way to maintain perfect accuracy in computer arithmetic.

Similar Questions