Fraction to Recurring Decimal - Problem

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

The challenge is that some fractions have repeating decimal parts. For example, 1/3 = 0.333... where 3 repeats infinitely. When this happens, you must enclose the repeating part in parentheses.

Examples:

  • 1/2 = "0.5" (finite decimal)
  • 1/3 = "0.(3)" (repeating decimal)
  • 22/7 = "3.(142857)" (repeating cycle)

If the fraction can be represented as a finite decimal, return it without parentheses. The key insight is detecting when remainders start repeating during long division - that's when the decimal cycle begins!

Input & Output

example_1.py โ€” Simple Fraction
$ Input: numerator = 1, denominator = 2
โ€บ Output: "0.5"
๐Ÿ’ก Note: 1/2 = 0.5, which is a finite decimal, so no parentheses are needed.
example_2.py โ€” Repeating Single Digit
$ Input: numerator = 1, denominator = 3
โ€บ Output: "0.(3)"
๐Ÿ’ก Note: 1/3 = 0.333..., where 3 repeats indefinitely, so we enclose it in parentheses.
example_3.py โ€” Longer Repeating Cycle
$ Input: numerator = 22, denominator = 7
โ€บ Output: "3.(142857)"
๐Ÿ’ก Note: 22/7 = 3.142857142857..., where 142857 repeats, forming a 6-digit cycle.

Constraints

  • -231 โ‰ค numerator, denominator โ‰ค 231 - 1
  • denominator โ‰  0
  • The length of the answer string is less than 104

Visualization

Tap to expand
๐Ÿ” Long Division Detective: 1 รท 3Step 1: Setup InvestigationInteger part: 1 รท 3 = 0, remainder = 1Hash map: {} (empty), Result so far: "0."Step 2: First Clue FoundRemainder 1 at position 2: 1ร—10=10, 10รท3=3, new remainder=1Step 3: ๐Ÿšจ Repeat Detected!Remainder 1 seen again! Cycle starts at position 2Step 4: Case Closed โœ“Insert parentheses: "0.3" โ†’ "0.(3)"๐Ÿ’กKey Insight: Same remainder = Same future sequence!
Understanding the Visualization
1
Setup Investigation
Handle the sign and calculate the integer part. Start tracking remainders with a hash map.
2
Follow the Trail
For each remainder in long division, check if we've seen it before. If not, record it with its position.
3
Catch the Repeat
The moment we see a repeated remainder, we've found our cycle! Insert parentheses around the repeating part.
4
Case Closed
Return the properly formatted decimal string with repeating parts in parentheses.
Key Takeaway
๐ŸŽฏ Key Insight: In long division, when the same remainder appears twice, the sequence of digits will repeat exactly from that point forward. Using a hash map to track remainder positions allows us to detect this cycle instantly and format the result correctly.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
73.2K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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