1827. Base-B Column Difference

Medium3.5 points estimatedMathsStringSimulation3 hints

A warehouse system stores stock counts as text in a base between 2 and 36, using the digits 0 to 9 and then the lowercase letters a to z. To find how far an actual count a is from an expected count b, it subtracts them column by column, borrowing from the next column whenever a column goes below zero.

Return a - b as text in the same base. If a is smaller than b, put a single minus sign in front of the result. The result has no leading zeros, and zero is written as 0 with no sign. Do not convert the strings to built-in integers. Aim for O(n + m) time, where n and m are the lengths of a and b.

Example 1

Input:
a = "256", b = "1212", base = 8
Output:
"-734"
Explanation:

256 (octal) is 174 and 1212 (octal) is 650, so the difference is -476, which is -734 in octal.

Example 2

Input:
a = "1000", b = "1", base = 2
Output:
"111"
Explanation:

8 - 1 = 7, which is 111 in binary, so the borrow runs through the three zeros.

Example 3

Input:
a = "abc", b = "abc", base = 16
Output:
"0"
Explanation:

Equal numbers give 0 with no sign.

Constraints

2 ≤ base ≤ 36

1 ≤ a.length, b.length ≤ 500

every digit is smaller than base; no leading zeros except the single string "0"

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n + m)
Space
O(n + m)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…