Problem Description
Given a 0-indexed integer array nums, repeatedly perform the following operations until nums becomes empty: if the array contains more than one element, remove the first and last elements, concatenate them (by placing the first element's digits in front of the last element's digits), and add the result to a running total; if only one element remains, add its value to the total and remove it. Return the final total, known as the concatenation value.
Key Insights
- Use two pointers (one at the beginning and one at the end) to simulate the removal process.
- Concatenating two numbers can be achieved by multiplying the first number by 10^(number of digits of the second number) and then adding the second number.
- The process runs in linear time relative to the length of the array.
- Handle the edge case where there is one element left.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
We utilize a two pointers approach, with one pointer starting at the beginning of the array and the other at the end. During each iteration, if both pointers refer to different elements, we compute the concatenated number by determining the number of digits in the second element and then adding first * (10^digits) + last to the result. The pointers are then moved inward. If the pointers meet (indicating a single remaining element), we add that element to the result and terminate. This method ensures that each element is processed once, making the solution efficient.