Subtract Two Numbers represented as Linked Lists
Given two linked lists representing numbers, subtract the smaller from the larger and return the result as a linked list.
Example: l1 = [7,8,5,6,3], l2 = [8,4,2] → 78563 - 842 = 77721
Sample Input
—
Sample Output
—
Constraints
- 1 to 10^4 nodes per list
Topics
Pad + Subtract with Borrow
function subtractLists(l1, l2) {
function toNum(l) { let n = 0n; while (l) { n = n*10n + BigInt(l.val); l = l.next; } return n; }
let diff = toNum(l1) - toNum(l2);
if (diff < 0n) diff = -diff;
const s = diff.toString(); let head = null, tail = null;
for (const c of s) {
const node = {val: parseInt(c), next: null};
if (!head) head = tail = node; else { tail.next = node; tail = node; }
}
return head || {val: 0, next: null};
}
Time: O(m + n) | Space: O(max(m,n))
Saved in this browser only. Private to you.