Fraction to Recurring Decimal - Problem

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses. For example, 1/3 = 0.(3) where 3 repeats infinitely.

If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs.

Note: If the fraction can be represented as a finite length string, you must return it without parentheses.

Input & Output

Example 1 — Simple Repeating Decimal
$ Input: numerator = 1, denominator = 3
Output: "0.(3)"
💡 Note: 1 ÷ 3 = 0.333... The digit 3 repeats infinitely, so we enclose it in parentheses: 0.(3)
Example 2 — Finite Decimal
$ Input: numerator = 1, denominator = 2
Output: "0.5"
💡 Note: 1 ÷ 2 = 0.5 exactly. Since it terminates, no parentheses are needed.
Example 3 — Negative with Repetition
$ Input: numerator = -1, denominator = 6
Output: "-0.1(6)"
💡 Note: -1 ÷ 6 = -0.1666... The digit 6 repeats after the initial 1, so result is -0.1(6)

Constraints

  • -231 ≤ numerator, denominator ≤ 231 - 1
  • denominator ≠ 0

Visualization

Tap to expand
Fraction to Recurring Decimal INPUT 1 numerator ÷ 3 denominator Long Division Process: 0.333... 3 | 1.000... remainder 1 remainder 1 repeats! Find string representation Mark repeating decimals with parentheses ALGORITHM STEPS 1 Handle Sign Check if result negative 2 Integer Part 1 / 3 = 0, rem = 1 3 Track Remainders HashMap: rem --> position 4 Detect Cycle If rem seen, add ( ) HashMap State: Remainder Index 1 2 rem 1 seen again! Insert ( at index 2 FINAL RESULT String Construction: Step 1: "0" Step 2: "0." Step 3: "0.3" Step 4: "0.(3)" Cycle detected at '3' OUTPUT: "0.(3)" Verification: OK 0.333... = 0.(3) Key Insight: A repeating decimal occurs when we see the same remainder twice during division. By storing each remainder and its position in a HashMap, we can detect when a cycle begins and insert parentheses at the exact position where the repetition starts. Time: O(d), Space: O(d) where d = denominator. TutorialsPoint - Fraction to Recurring Decimal | Hash Map Optimization
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
89.4K Views
Medium Frequency
~35 min Avg. Time
1.5K 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