Skip to problem
←

Subtract Two Numbers Represented as Linked Lists

Hard 0 attempts

You're given two numbers, each represented as a linked list of digits. Digits are stored most significant first. Subtract the smaller number from the larger one and return the non-negative result in the same order, without leading zeros except for a single zero node when the numbers are equal.

The input lists may have leading zeros, and either list may represent the larger number. Each node holds one decimal digit in val, with next pointing to the following digit. Return a list head, not an array or a JavaScript number.

The numbers may contain 10,000 digits, so converting them to Number loses precision. For example, [0,0,1] and [2] represent 1 and 2, giving [1].

Function contract

Implement subtractLists(l1, l2). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the absolute difference as a most-significant-digit-first list. Remove leading zeros; zero must be represented by one node with val = 0.

Example 1

Input
l1 = [1,0,0]
l2 = [1]
Output
[9,9]

Example 2

Input
l1 = [1]
l2 = [1]
Output
[0]
Constraints
  • 1 to 10^4 nodes per list
  • Each node contains an integer digit from 0 through 9
  • Leading zeros are allowed in the input lists
Topics

Digit-by-Digit Subtraction

Copy digits into arrays and skip their leading zeros. Compare significant lengths, then digits lexicographically, to put the larger number first. Work from right to left, carrying a borrow into the next position. Prepend each result digit so the returned list remains most-significant-first.

This avoids whole-number conversion and leaves both input lists unchanged.

javascript
function subtractLists(l1, l2) {
  function digits(node) {
    const values = [];
    for (; node; node = node.next) values.push(node.val);
    let start = 0;
    while (start < values.length - 1 && values[start] === 0) start++;
    return values.slice(start);
  }
  let a = digits(l1), b = digits(l2);
  let comparison = a.length - b.length;
  if (comparison === 0) {
    for (let i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) { comparison = a[i] - b[i]; break; }
    }
  }
  if (comparison < 0) [a, b] = [b, a];
  let i = a.length - 1, j = b.length - 1, borrow = 0, head = null;
  while (i >= 0) {
    let value = a[i--] - (j >= 0 ? b[j--] : 0) - borrow;
    borrow = value < 0 ? 1 : 0;
    if (borrow) value += 10;
    head = {val: value, next: head};
  }
  while (head.next && head.val === 0) head = head.next;
  return head;
}

Time: O(m + n), where m and n are the input lengths.

Space: O(m + n) for digit arrays and the result list.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript