Fraction Addition and Subtraction

MediumMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string expression that adds and subtracts fractions, such as "-1/2+1/3". Each fraction is written as numerator/denominator using positive integers, and fractions are joined by + or -. The first fraction may be preceded by a - sign; it is never preceded by +. Evaluate the expression and return the result as a string "a/b" in lowest terms, where b > 0 and the sign (if negative) is carried on a. A whole-number result still uses a denominator: 2 is written "2/1" and zero is written "0/1".

Examples

Input: expression = "-1/2+1/2"
Output: "0/1"
The two fractions cancel, and zero is written with denominator 1.
Input: expression = "-1/2+1/2+1/3"
Output: "1/3"
The first two terms cancel, leaving `1/3`.
Input: expression = "1/3-1/2"
Output: "-1/6"
`2/6 - 3/6 = -1/6`.

Constraints

  • `1 <= number of fractions <= 10`
  • Every numerator and denominator is an integer in `[1, 10]`
  • `expression` contains only digits, `/`, `+`, and `-`, and is well formed

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems