1593. Chain Subtraction

Medium3.5 points estimatedLinked ListMathsStack

Two very long account numbers are stored digit by digit in singly linked lists a and b, most significant digit first, and leading zeros may appear. Write chainDifference(a, b), which returns the absolute difference |a - b| as a new linked list of digits, most significant first, with no leading zeros; when the numbers are equal return a single node holding 0. Compare the two numbers first (by length after skipping leading zeros, then digit by digit), then subtract the smaller from the larger from the tail upwards with borrows, for instance with arrays or a stack. Each list has 1 to 100000 digits between 0 and 9, so built-in big integers are not the intended route. Aim for O(n) time.

Example 1

Input:
a = [1,2,3], b = [4,5]
Output:
[7,8]
Explanation:

123 - 45 = 78.

Example 2

Input:
a = [1,0,0], b = [9,9]
Output:
[1]
Explanation:

The borrow runs through every digit: 100 - 99 = 1.

Example 3

Input:
a = [0,0,5], b = [0,5]
Output:
[0]
Explanation:

Both numbers equal 5 after ignoring leading zeros, so the result is a single 0.

Constraints

1 ≤ length of a, length of b ≤ 105

0 ≤ val ≤ 9

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

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…