21(June) Compare two fractions

21. Compare Two Fractions

The problem can be found at the following link: Question Link

Problem Description

You are given a string str containing two fractions a/b and c/d. Compare these fractions and return the greater. If they are equal, then return "equal".

Note: The string str contains "a/b, c/d" (fractions are separated by a comma , and a space ).

Examples:

Input:

str = "5/6, 11/45"

Output:

5/6

Explanation: 5/6 = 0.8333 and 11/45 = 0.2444, so 5/6 is the greater fraction.

My Approach

  1. Parse the Input String:

    • Split the input string str into two parts using ", " as the delimiter to separate the fractions.

    • Extract the numerator and denominator for each fraction by splitting each part using '/'.

  2. Compare the Fractions:

    • Calculate the cross multiplication for comparison:

      • Compare a * d with b * c.

    • Based on the comparison:

      • Return the greater fraction as a string.

      • If they are equal, return "equal".

  3. Return the Result:

    • Return the greater fraction in string format or "equal" if both fractions are the same.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(len(str)), as we perform operations proportional to the length of the input string.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated