Equal Rational Numbers - Problem

Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.

A rational number can be represented using up to three parts:

  • IntegerPart: For example, 12, 0, and 123.
  • IntegerPart.NonRepeatingPart: For example, 0.5, 1., 2.12, and 123.0001.
  • IntegerPart.NonRepeatingPart(RepeatingPart): For example, 0.1(6), 1.(9), 123.00(1212).

The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example: 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).

Input & Output

Example 1 — Same Rational Number
$ Input: s = "0.(52)", t = "0.5(25)"
Output: true
💡 Note: Both represent the same repeating decimal 0.525252..., just with different groupings of the repeating part.
Example 2 — Different Numbers
$ Input: s = "0.1666(6)", t = "0.166(66)"
Output: true
💡 Note: Both represent 1/6 = 0.16666..., showing different valid representations of the same repeating pattern.
Example 3 — No Repeating vs Repeating
$ Input: s = "0.9(9)", t = "1."
Output: true
💡 Note: 0.9999... equals exactly 1.0, demonstrating the mathematical equivalence.

Constraints

  • Each string contains only digits, '.', '(', ')'
  • Both strings are valid representations of rational numbers
  • No leading zeros except for numbers less than 1
  • 1 ≤ s.length, t.length ≤ 20

Visualization

Tap to expand
Equal Rational Numbers INPUT String s = "0.(52)" 0 . (52) repeating String t = "0.5(25)" 0 . 5 (25) repeating Format Structure: IntegerPart IntegerPart.NonRepeating IntegerPart.NonRep(Rep) () = repeating decimal ALGORITHM STEPS 1 Parse Components Extract int, non-rep, rep parts 2 Expand Repeating Repeat pattern ~20 times 3 Convert to Double Parse expanded decimal 4 Compare Values Check if doubles equal Expansion Process: s: 0.(52) --> 0.525252... t: 0.5(25) --> 0.525252... Both expand to same 0.52525252525252... = 52/99 FINAL RESULT Comparison 0.5252... == 0.5252... EQUAL! Output: true Verification s value: 0.52525252525... t value: 0.52525252525... OK - Same Number! Key Insight: Different decimal notations can represent the same rational number. "0.(52)" means 0.525252... while "0.5(25)" means 0.525252... - both equal 52/99. By expanding the repeating part sufficiently (20+ repetitions) and comparing as floating-point, we can determine equality. TutorialsPoint - Equal Rational Numbers | Optimal Solution
Asked in
Google 15 Facebook 12 Microsoft 8
28.5K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen