#166
Fraction to Recurring Decimal
MediumHash TableMathStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution utilizes a hashmap to keep track of previously seen remainders, allowing us to efficiently identify repeating cycles in the decimal representation. This reduces unnecessary calculations and improves performance.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the integer part and handle the sign.
- 2Step 2: Use a hashmap to store the index of each remainder encountered during the division process.
- 3Step 3: When a remainder repeats, we can determine the start of the repeating section and format the result accordingly.
solution.py26 lines
1# Full working Python code
2
3def fractionToDecimal(numerator: int, denominator: int) -> str:
4 if numerator == 0:
5 return '0'
6 result = ''
7 if (numerator < 0) ^ (denominator < 0):
8 result += '-'
9 numerator, denominator = abs(numerator), abs(denominator)
10 integer_part = numerator // denominator
11 result += str(integer_part)
12 remainder = numerator % denominator
13 if remainder == 0:
14 return result
15 result += '.'
16 remainder_map = {}
17 decimal_part = ''
18 while remainder != 0:
19 if remainder in remainder_map:
20 decimal_part = decimal_part[:remainder_map[remainder]] + '({})'.format(decimal_part[remainder_map[remainder]:])
21 break
22 remainder_map[remainder] = len(decimal_part)
23 remainder *= 10
24 decimal_part += str(remainder // denominator)
25 remainder %= denominator
26 return result + decimal_partℹ
Complexity note: The complexity is O(n) because we process each digit of the decimal representation only once, and we store remainders in a hashmap for quick access.
- 1Understanding how to perform long division is crucial for this problem.
- 2Recognizing when a remainder repeats helps identify the start of a recurring decimal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.