Add one to a number represented by LL

Linked-List FAQs (Medium) Medium

Given the head of a singly linked list representing a positive integer number. Each node of the linked list represents a digit of the number, with the 1st node containing the leftmost digit of the number and so on. The task is to add one to the value represented by the linked list and return the head of a linked list containing the final value.


The number will contain no leading zeroes except when the value represented is zero itself.

Examples:

Input: head -> 1 -> 2 -> 3

Output: head -> 1 -> 2 -> 4

Explanation: The number represented by the linked list = 123.

123 + 1 = 124.

Input: head -> 9 -> 9

Output: head -> 1 -> 0 -> 0

Explanation: The number represented by the linked list = 99.

99 + 1 = 100.

Input: head -> 9

Constraints

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 9
  • No leading zeroes in the value represented.

Hints

  • A brute-force approach involves Converting the linked list to an integer (O(n)). Adding 1, then reconstructing the linked list (O(n)). Drawback: Uses extra memory (O(n)) for number conversion.
  • Reverse the linked list (O(n)) to make the least significant digit the head. Perform normal addition with carry (O(n)). Reverse the linked list back (O(n)) to restore order.

Company Tags

Nutanix Teladoc Health PwC GE Healthcare JPMorgan Chase Goldman Sachs Shopify OYO Rooms DoorDash Siemens Healthineers Activision Blizzard HashiCorp Zynga Dropbox Rockstar Games Intel Airbnb Splunk Alibaba ARM Cloudflare Freshworks Micron Technology Boston Consulting Group Roblox Google Microsoft Amazon Meta Apple Netflix Adobe