Plus One Linked List

Pattern: Reversal

medium

Adding 1 changes the last digit that is not a 9 (it goes up by one) and turns every 9 after it into 0. A spare 0 node in front handles numbers made only of 9s.

The problem

A non-negative whole number is stored in a linked list, one digit per node, most significant digit first, with no leading zeros except the number 0 itself. Add one to it and return the head of the result. For example, 1 → 2 → 3 becomes 1 → 2 → 4, 1 → 9 → 9 becomes 2 → 0 → 0, and 9 → 9 becomes 1 → 0 → 0.

The function name plusOne matches LeetCode, where this problem needs a premium account. Use the link above for the exact statement and limits.

Think first

  • When you add 1 by hand, which digits change?
  • Can you find them without walking backwards?
  • What if every digit is 9?

Hints

    Brute force, and why it fails

    Reverse the list, add with a carry, reverse back: O(n) and correct, but three passes. Converting to a number overflows for long lists. Finding the last non-9 digit is one pass plus the rollover.

    The key insight

    The carry from adding 1 stops at the first digit, from the right, that is not 9. Finding that digit from the left is just "remember the last one you saw".

    Dry run

    00 
    11 
    92 
    93 

    The list is 1 → 9 → 9, the number 199. A spare node with 0 goes in front.

    Step 1 of 4

    The plan

    dummy = new node(0, next = head)
    lastNotNine = dummy
    for each node cur: if cur.val != 9: lastNotNine = cur
    lastNotNine.val = lastNotNine.val + 1
    set every node after lastNotNine to 0
    return dummy if dummy.val == 1 else dummy.next
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two short walks and one extra node.

    Edge cases

    • All 9s: the answer has one more digit.
    • Last digit not 9: only it changes.
    • The number 0: 1.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode plusOne(ListNode head) {
            ListNode dummy = new ListNode(0);       // a spare 0 in front, in case the number grows a digit
            dummy.next = head;
            ListNode lastNotNine = dummy;
            for (ListNode cur = head; cur != null; cur = cur.next) if (cur.val != 9) lastNotNine = cur;
            lastNotNine.val++;                      // that digit goes up by one
            for (ListNode cur = lastNotNine.next; cur != null; cur = cur.next) cur.val = 0;   // the 9s after it roll over
            return dummy.val == 0 ? dummy.next : dummy;
        }
    }

    C++

    class Solution {
    public:
        ListNode* plusOne(ListNode* head) {
            ListNode* dummy = new ListNode(0);      // a spare 0 in front, in case the number grows a digit
            dummy->next = head;
            ListNode* lastNotNine = dummy;
            for (ListNode* cur = head; cur != NULL; cur = cur->next) if (cur->val != 9) lastNotNine = cur;
            lastNotNine->val++;                     // that digit goes up by one
            for (ListNode* cur = lastNotNine->next; cur != NULL; cur = cur->next) cur->val = 0;   // the 9s roll over
            return dummy->val == 0 ? dummy->next : dummy;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def plusOne(self, head: ListNode) -> ListNode:
            dummy = ListNode(0, head)               # a spare 0 in front, in case the number grows a digit
            last_not_nine, cur = dummy, head
            while cur is not None:
                if cur.val != 9:
                    last_not_nine = cur
                cur = cur.next
            last_not_nine.val += 1                  # that digit goes up by one
            cur = last_not_nine.next
            while cur is not None:                  # the 9s after it roll over
                cur.val = 0
                cur = cur.next
            return dummy.next if dummy.val == 0 else dummy

    Common mistakes

    • Changing only the last digit, which breaks for trailing 9s.
    • Forgetting the all-9s case.
    • Converting to an integer type, which overflows for long numbers.

    Similar problems