VOOZH about

URL: https://www.geeksforgeeks.org/dsa/subtract-two-numbers-represented-as-linked-lists/

⇱ Subtract Two Numbers represented as Linked Lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subtract Two Numbers represented as Linked Lists

Last Updated : 20 Apr, 2026

You are given two linked lists representing two large positive numbers. The linked lists represent these two numbers, subtract the smaller number from the larger one and return the head of the linked list representing the result.

The linked list does not contain leading zeros, except for the number zero itself.

Examples:

Input: l1 = 1 -> 0 -> 0 -> NULL, l2 = 1 -> NULL
Output: 9->9->NULL
Explanation: Number represented as lists are 100 and 1, so 100 - 1 is 99

Input: l1 = 7-> 8 -> 6 -> NULL, l2 = 7 -> 8 -> 9 NULL
Output: 3->NULL
Explanation: Number represented as lists are 786 and 789, so 789 - 786 is 3, as the smaller value is subtracted from the larger one.

Using Recursion - O(m + n) Time and O(max(m, n)) Auxiliary Space

We subtract two numbers represented as linked lists where digits are stored in forward order. Since subtraction naturally happens from the rightmost digit, we use recursion to reach the end of the lists and perform subtraction while backtracking. Before that, we equalize their sizes by padding zeros. During subtraction, we handle borrow just like in manual subtraction and finally remove leading zeros.

  • Find sizes and pad zeros to make both linked lists equal
  • Ensure subtraction is always (larger − smaller)
  • Use recursion to reach the last node (for right-to-left processing)
  • During backtracking, subtract digits and handle borrow
  • If needed, add 10 to current digit and set borrow
  • Create and link result nodes, then remove leading zeros

Output
9 9 

Reversing Both Linked Lists - O(m + n) Time and O(max(m, n)) Space

In this approach, we reverse both linked lists so that subtraction can be done from the least significant digit (just like normal subtraction). Then we traverse both lists together, subtract digits while handling borrow, and build the result list. Finally, we reverse the result back and remove any leading zeros.

  • Reverse both linked lists so subtraction starts from least significant digits
  • Initialize pointers for both lists and a borrow variable (initially 0)
  • Traverse both lists together, subtract digits while adjusting for borrow
  • If current digit is smaller, add 10 and set borrow for next step
  • Create new nodes with the subtraction result and append to result list
  • Reverse the result list and remove leading zeros before returning

Below is the implementation of the above approach:


Output
9 9 
Comment