LeetCode Daily 24/09/2025 - 166. Fraction to Recurring Decimal
Problem Link
LeetCode 166 - Fraction to Recurring Decimal
Difficulty: Medium
Topic: Hash Table, Math, String
Daily Question: 24th September 2025
Problem Recap
Given two integers representing the numerator and denominator of a fraction, we need to return the fraction in string format. The key challenge is handling recurring decimal patterns properly.
Requirements:
- If the fractional part repeats, enclose the repeating part in parentheses
- Handle negative signs correctly (only when numerator and denominator have different signs)
- Return integer part only if there’s no fractional remainder
- The answer string length is guaranteed to be less than 10⁴
Examples:
1/2 = "0.5"(terminating decimal)4/333 = "0.(012)"(recurring decimal)2/1 = "2"(integer result)
Intuition
This problem is fundamentally about long division simulation. The key insight is that recurring decimals occur when we encounter the same remainder twice during division.
Think about manual long division:
- We divide, get a quotient and remainder
- Multiply remainder by 10, divide again
- If we see the same remainder again, we’ve found our cycle!
The challenge lies in:
- Detecting cycles: Use hash table to track remainder positions
- Handling signs: XOR to determine if result should be negative
- Building result: Carefully construct string with parentheses at correct positions
Approach
Step 1: Handle Edge Cases and Signs
- If numerator is 0, return “0”
- Calculate sign using XOR: negative if exactly one of numerator/denominator is negative
- Work with absolute values to simplify logic
Step 2: Integer Division
- Calculate integer part:
n // d - Get initial remainder:
n % d - If remainder is 0, return integer result (no fractional part)
Step 3: Fractional Part with Cycle Detection
Key Data Structures:
res: List to build result string incrementallyseen: Hash map tracking{remainder: position_in_result}
Long Division Process:
- For each remainder, check if we’ve seen it before
- If yes → cycle detected! Insert opening parenthesis at stored position, append closing parenthesis
- If no → record current position, continue division
- Multiply remainder by 10, divide by denominator
- Append quotient digit, update remainder
Step 4: Result Construction
- Use list for efficient string building
- Insert parentheses at correct positions when cycle is detected
- Join all parts into final string
Complexity Analysis
- Time complexity:
O(d)where d is the denominator- In worst case, we might see d-1 different remainders before finding a cycle
- Each iteration involves constant time hash operations
- Space complexity:
O(d)for the hash map storing remainder positions
Solution
1 | class Solution: |
Example Walkthrough
Input: numerator = 4, denominator = 333
Step 1: Handle Signs and Integer Part
- Both positive →
sign = "" n = 4, d = 333integer = 4 // 333 = 0rem = 4 % 333 = 4- Since
rem ≠ 0, we have fractional part res = ["0", "."]
Step 2: Long Division Process
Iteration 1: rem = 4
4not inseen→seen[4] = 2(position after decimal point)rem = 4 * 10 = 4040 // 333 = 0→ append"0"rem = 40 % 333 = 40res = ["0", ".", "0"]
Iteration 2: rem = 40
40not inseen→seen[40] = 3rem = 40 * 10 = 400400 // 333 = 1→ append"1"rem = 400 % 333 = 67res = ["0", ".", "0", "1"]
Iteration 3: rem = 67
67not inseen→seen[67] = 4rem = 67 * 10 = 670670 // 333 = 2→ append"2"rem = 670 % 333 = 4res = ["0", ".", "0", "1", "2"]
Iteration 4: rem = 4
4already inseenat position2!- Cycle detected! Insert
"("at position2, append")" res = ["0", ".", "(", "0", "1", "2", ")"]
Result: "0.(012)"
Key Takeaways
- Long division simulation: The core algorithm mimics manual long division process
- Cycle detection with hash map: Track remainder positions to identify when repetition begins
- Sign handling: Use XOR for elegant negative sign determination
- String building strategy: Use list for efficiency, insert parentheses when cycle found
- Edge case handling: Zero numerator and integer-only results need special treatment
- Mathematical insight: Recurring decimals are inevitable when denominators have prime factors other than 2 and 5
This problem beautifully combines mathematical concepts with algorithmic techniques, demonstrating how hash tables can solve seemingly complex mathematical problems efficiently.
Part of my daily LeetCode journey! Follow along for more algorithm solutions and explanations.