You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.
Return the head of the linked list after doubling it.
Example 1:
Input: head = [1,8,9] Output: [3,7,8] Explanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.
Example 2:
Input: head = [9,9,9] Output: [1,9,9,8] Explanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998.
Constraints:
[1, 104]0 <= Node.val <= 90 itself.This approach utilizes binary search to efficiently find the target element in a sorted array. Since the array is sorted, binary search can be applied, reducing the time complexity significantly compared to a linear search.
The core idea is to repeatedly divide the search interval in half. If the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half until the target is found or the interval is empty.
This C code implements a binary search. It initializes two pointers, left and right, and iteratively adjusts them based on comparisons with the middle element of the active subarray. When the target is found, it immediately returns the index. If not found, it returns -1.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n), where n is the number of elements in the array.
Space Complexity: O(1), as no extra space is utilized.
The two-pointer approach helps to solve the problem with pointers or two index variables. This technique is beneficial when you need to minimize the number of iterations or traverse the array with controlled steps. Often used in problems involving arrays, especially when the sum or difference needs to be calculated between distinct elements.
This C code solves the problem using two pointers: one pointing to the start of the array, and the other pointing to the end. If the sum of the values at these two pointers matches the target, a flag is set. Otherwise, the pointers are adjusted to optimize towards the condition.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as no extra space is consumed.
| Approach | Complexity |
|---|---|
| Binary Search Approach | Time Complexity: O(log n), where n is the number of elements in the array. |
| Two-Pointer Technique | Time Complexity: O(n), where n is the number of elements in the array. |
2816. Double a Number Represented as a Linked List | 5 Approaches | Two Pointers | One Pointer • Aryan Mittal • 1,946 views views
Watch 9 more video solutions →Practice Double a Number Represented as a Linked List with our built-in code editor and test cases.
Practice on FleetCode