Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Fraction to Recurring Decimal

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "166" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 104 for all the given inputs. Example 1: Input: numerator = 1, denominator = 2 Output: "0.5" Example 2: Input: numerator = 2, denominator = 1 Output: "2" Example 3: Input: numerator = 4, denominator = 333 Output: "0.(012)" Constraints: -231 <= numerator, denominator <= 231 - 1 denominator != 0

Explanation

Here's the breakdown of the solution:

  • Handle Signs and Integer Part: Determine the sign of the result and compute the integer part of the fraction.
  • Detect Repeating Decimal: Use a dictionary (hash map) to store remainders encountered during the division process. If a remainder repeats, it indicates a repeating decimal.
  • Build String: Construct the string representation of the fraction, adding parentheses around the repeating part if necessary.

  • Runtime Complexity: O(n), where n is the length of the repeating decimal. Storage Complexity: O(n), due to the dictionary storing remainders.

Code

    def fraction_to_decimal(numerator: int, denominator: int) -> str:
    """
    Converts a fraction to its decimal representation.
    """

    if numerator == 0:
        return "0"

    sign = "-" if (numerator < 0) ^ (denominator < 0) else ""
    numerator = abs(numerator)
    denominator = abs(denominator)

    integer_part = numerator // denominator
    remainder = numerator % denominator

    if remainder == 0:
        return sign + str(integer_part)

    decimal_part = ""
    remainder_map = {}  # Store remainders and their positions

    while remainder != 0:
        if remainder in remainder_map:
            # Repeating decimal found
            insert_pos = remainder_map[remainder]
            decimal_part = decimal_part[:insert_pos] + "(" + decimal_part[insert_pos:] + ")"
            return sign + str(integer_part) + "." + decimal_part

        remainder_map[remainder] = len(decimal_part)
        remainder *= 10
        decimal_part += str(remainder // denominator)
        remainder %= denominator

    return sign + str(integer_part) + "." + decimal_part

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Fraction to Recurring Decimal