FunctionRacerProblemsRace

Subtract Two Numbers

HardLinked listsPython, JavaScript, TypeScript, Java, C++

Each of the two lists spells a number: one digit per node, starting with the leading digit. There are no zeros in front, except that the number 0 is a single node. Which of the two is larger is not known.

Take the smaller number away from the larger one and return what is left as a list of the same kind. Equal numbers give a single node holding 0. A number may have up to 30 digits, so in most languages it has to be handled digit by digit. The lists are passed in as first and second.

Linked lists appear in the tests as the list of their values, like [1,2,3]. Each node is a ListNode with .val and .next; the class is already defined for you.

Example 1

first [1,0,0]
second [1]
returns [9,9]

100 minus 1 is 99: the borrow runs through both zeros, and the answer is one digit shorter.

Example 2

first [3]
second [1,2]
returns [9]

The second number is the larger one: 12 minus 3 is 9.

Example 3

first [5]
second [5]
returns [0]

Equal numbers leave 0.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Linked lists problems