2562. Find the Array Concatenation Value
Problem Description
You are given a 0-indexed integer array nums
. Your task is to calculate the concatenation value of this array through a specific process.
Concatenation means joining two numbers together as strings. For example, concatenating 15 and 49 gives 1549 (not 64, which would be addition).
Starting with a concatenation value of 0, you need to repeatedly perform the following operation until the array becomes empty:
-
If the array has more than one element: Take the first and last elements, concatenate them (join them as strings to form a new number), add this concatenated number to your running total, and remove both elements from the array.
- Example: If
nums = [1, 2, 4, 5, 6]
, you would concatenate 1 and 6 to get 16, add 16 to your total, and remove both 1 and 6 from the array.
- Example: If
-
If the array has exactly one element: Simply add that element's value to your running total and remove it from the array.
The process continues until all elements are removed from the array. Return the final concatenation value.
Example walkthrough:
- For
nums = [1, 2, 4, 5, 6]
:- First iteration: Concatenate 1 and 6 β 16, add to total (total = 16)
- Second iteration: Concatenate 2 and 5 β 25, add to total (total = 41)
- Third iteration: Only 4 remains, add 4 to total (total = 45)
- Return 45
Intuition
The problem asks us to repeatedly take elements from both ends of the array and concatenate them. This immediately suggests using a two-pointer approach - one pointer starting from the beginning and another from the end of the array.
Think about how we would manually solve this problem: we'd look at the first element, look at the last element, combine them, and then move inward. This is exactly what two pointers can do efficiently.
The key insight is that we don't actually need to modify the array by removing elements. Instead, we can simulate this process by:
- Maintaining a left pointer
i
starting at index 0 - Maintaining a right pointer
j
starting at the last index - Moving both pointers toward each other after each concatenation
For concatenation, we need to join two numbers as strings. The straightforward way is to convert both numbers to strings using str()
, concatenate them with +
, and then convert back to an integer using int()
. So for numbers a
and b
, the concatenation would be int(str(a) + str(b))
.
The process continues while i < j
, meaning we still have at least two elements to process. When the pointers meet (i == j
), we have exactly one element left in the middle, which we simply add to our result without any concatenation.
This approach is elegant because:
- We avoid the costly operation of actually removing elements from the array
- We process the array in a single pass with O(n) time complexity
- The logic naturally handles both even and odd-length arrays
Learn more about Two Pointers patterns.
Solution Approach
We implement the solution using the two-pointer technique to simulate the process of taking elements from both ends of the array.
Step-by-step implementation:
-
Initialize variables:
ans = 0
to store the concatenation valuei = 0
as the left pointer starting from the beginningj = len(nums) - 1
as the right pointer starting from the end
-
Process pairs of elements:
- While
i < j
, we have at least two elements to process - Convert both
nums[i]
andnums[j]
to strings usingstr()
- Concatenate them:
str(nums[i]) + str(nums[j])
- Convert the concatenated string back to integer:
int(str(nums[i]) + str(nums[j]))
- Add this value to
ans
- Move the pointers inward:
i = i + 1
andj = j - 1
- While
-
Handle the middle element (if exists):
- After the loop, if
i == j
, there's exactly one element left in the middle - Simply add
nums[i]
toans
without any concatenation
- After the loop, if
-
Return the result:
- Return
ans
as the final concatenation value
- Return
Example walkthrough with nums = [7, 52, 2, 4]
:
- Initial:
i = 0, j = 3, ans = 0
- First iteration: Concatenate 7 and 4 β
74
,ans = 74
, move toi = 1, j = 2
- Second iteration: Concatenate 52 and 2 β
522
,ans = 74 + 522 = 596
, move toi = 2, j = 1
- Loop ends since
i >= j
- No middle element since
i > j
- Return
596
Time Complexity: O(n) where n is the length of the array, as we visit each element exactly once.
Space Complexity: O(1) as we only use a constant amount of extra space for the pointers and the answer variable.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [3, 8, 15, 9]
:
Initial Setup:
- Two pointers:
i = 0
(pointing to 3),j = 3
(pointing to 9) ans = 0
(our running total)
Step 1: Process first pair (i=0, j=3)
- Elements:
nums[0] = 3
andnums[3] = 9
- Concatenate:
str(3) + str(9) = "3" + "9" = "39"
- Convert to integer:
int("39") = 39
- Update total:
ans = 0 + 39 = 39
- Move pointers inward:
i = 1
,j = 2
Step 2: Process second pair (i=1, j=2)
- Elements:
nums[1] = 8
andnums[2] = 15
- Concatenate:
str(8) + str(15) = "8" + "15" = "815"
- Convert to integer:
int("815") = 815
- Update total:
ans = 39 + 815 = 854
- Move pointers inward:
i = 2
,j = 1
Step 3: Check for middle element
- Now
i = 2
andj = 1
, soi > j
- No middle element exists (array had even length)
- Process complete
Final Result: Return ans = 854
The two-pointer approach efficiently processes the array from both ends without actually removing elements, completing in just n/2 iterations for an array of length n.
Solution Implementation
1class Solution:
2 def findTheArrayConcVal(self, nums: List[int]) -> int:
3 """
4 Calculate the concatenation value of an array by concatenating elements
5 from both ends and summing the results.
6
7 Args:
8 nums: List of integers
9
10 Returns:
11 The sum of concatenated values
12 """
13 # Initialize the result sum
14 total_sum = 0
15
16 # Set up two pointers: one at the start and one at the end
17 left_index = 0
18 right_index = len(nums) - 1
19
20 # Process pairs of elements from both ends
21 while left_index < right_index:
22 # Concatenate the left and right numbers as strings, then convert back to integer
23 concatenated_value = int(str(nums[left_index]) + str(nums[right_index]))
24 total_sum += concatenated_value
25
26 # Move pointers towards the center
27 left_index += 1
28 right_index -= 1
29
30 # Handle the middle element if the array has odd length
31 if left_index == right_index:
32 total_sum += nums[left_index]
33
34 return total_sum
35
1class Solution {
2 /**
3 * Finds the concatenation value of an array by concatenating elements from both ends.
4 * The concatenation value is calculated by pairing elements from the start and end of the array,
5 * concatenating them as strings, converting back to integers, and summing all values.
6 * If the array has odd length, the middle element is added directly.
7 *
8 * @param nums the input integer array
9 * @return the total concatenation value of the array
10 */
11 public long findTheArrayConcVal(int[] nums) {
12 long totalSum = 0;
13 int leftIndex = 0;
14 int rightIndex = nums.length - 1;
15
16 // Process pairs of elements from both ends moving towards the center
17 while (leftIndex < rightIndex) {
18 // Concatenate left and right elements as strings, then parse to integer
19 String concatenated = String.valueOf(nums[leftIndex]) + String.valueOf(nums[rightIndex]);
20 totalSum += Integer.parseInt(concatenated);
21
22 // Move pointers towards the center
23 leftIndex++;
24 rightIndex--;
25 }
26
27 // If array has odd length, add the middle element
28 if (leftIndex == rightIndex) {
29 totalSum += nums[leftIndex];
30 }
31
32 return totalSum;
33 }
34}
35
1class Solution {
2public:
3 long long findTheArrayConcVal(vector<int>& nums) {
4 long long result = 0;
5 int left = 0;
6 int right = nums.size() - 1;
7
8 // Process pairs from both ends moving towards center
9 while (left < right) {
10 // Concatenate left and right numbers as strings, then convert back to integer
11 // For example: nums[left]=12, nums[right]=34 -> "12" + "34" = "1234" -> 1234
12 string concatenated = to_string(nums[left]) + to_string(nums[right]);
13 result += stoi(concatenated);
14
15 // Move pointers towards center
16 left++;
17 right--;
18 }
19
20 // If array has odd length, add the middle element
21 if (left == right) {
22 result += nums[left];
23 }
24
25 return result;
26 }
27};
28
1/**
2 * Calculates the concatenation value of an array by pairing elements from both ends
3 * @param nums - The input array of numbers
4 * @returns The sum of concatenated values
5 */
6function findTheArrayConcVal(nums: number[]): number {
7 const arrayLength: number = nums.length;
8 let totalSum: number = 0;
9 let leftIndex: number = 0;
10 let rightIndex: number = arrayLength - 1;
11
12 // Process pairs by concatenating elements from left and right ends
13 while (leftIndex < rightIndex) {
14 // Concatenate the left and right numbers as strings, then convert back to number
15 const concatenatedValue: number = Number(`${nums[leftIndex]}${nums[rightIndex]}`);
16 totalSum += concatenatedValue;
17
18 // Move pointers towards the center
19 leftIndex++;
20 rightIndex--;
21 }
22
23 // If array has odd length, add the middle element directly
24 if (leftIndex === rightIndex) {
25 totalSum += nums[leftIndex];
26 }
27
28 return totalSum;
29}
30
Time and Space Complexity
Time Complexity: O(n Γ log M)
The algorithm iterates through the array using two pointers that meet in the middle, performing n/2
iterations where n
is the length of the array. In each iteration, the main operation is concatenating two numbers by converting them to strings and back to an integer. Converting a number to a string takes O(log M)
time where M
is the maximum value in the array (since the number of digits in a number is proportional to log M
). The string concatenation and conversion back to integer also take O(log M)
time. Therefore, the overall time complexity is O(n/2 Γ log M) = O(n Γ log M)
.
Space Complexity: O(log M)
The space complexity comes from the temporary string objects created during the concatenation operation. When converting numbers to strings and concatenating them, the maximum space needed is proportional to the number of digits in the largest number, which is O(log M)
. The algorithm uses only a constant amount of additional variables (ans
, i
, j
), and the string concatenation creates temporary strings whose maximum length is bounded by 2 Γ log M = O(log M)
.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Incorrect String Concatenation Logic
A common mistake is trying to concatenate numbers mathematically instead of as strings. For example, attempting to concatenate 15 and 49 by calculating 15 * 100 + 49 = 1549
. While this might work for some cases, it fails when dealing with numbers that have leading zeros in their decimal representation or when the second number has varying digits.
Wrong approach:
# This fails for nums[j] = 0 or when nums[j] has varying digit counts
concatenated = nums[left] * (10 ** len(str(nums[right]))) + nums[right]
Correct approach:
concatenated = int(str(nums[left]) + str(nums[right]))
2. Forgetting to Handle the Middle Element
When the array has an odd length, there will be one element left in the middle after processing all pairs. Forgetting to add this element to the total sum will result in an incorrect answer.
Incomplete solution:
while left < right:
total += int(str(nums[left]) + str(nums[right]))
left += 1
right -= 1
# Missing: if left == right: total += nums[left]
return total
3. Off-by-One Error in Pointer Initialization
Initializing the right pointer incorrectly (e.g., right = len(nums)
instead of len(nums) - 1
) will cause an index out of bounds error.
Wrong initialization:
right_index = len(nums) # This will cause IndexError
Correct initialization:
right_index = len(nums) - 1
4. Using Wrong Loop Condition
Using <=
instead of <
in the while loop condition would process the middle element twice in arrays with odd length, leading to incorrect results.
Wrong condition:
while left_index <= right_index: # This processes middle element in the loop
concatenated = int(str(nums[left_index]) + str(nums[right_index]))
# When left_index == right_index, this concatenates the same element with itself
Correct condition:
while left_index < right_index: # Stop when pointers meet or cross
Is the following code DFS or BFS?
void search(Node root) { if (!root) return; visit(root); root.visited = true; for (Node node in root.adjacent) { if (!node.visited) { search(node); } } }
Recommended Readings
Tech Interview Pattern Two Pointers Introduction If you prefer videos here's a super quick introduction to Two Pointers div class responsive iframe iframe src https www youtube com embed xZ4AfXHQ1VQ title YouTube video player frameborder 0 allow accelerometer autoplay clipboard write encrypted media gyroscope picture in picture allowfullscreen iframe div Two pointers is a common interview
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Donβt Miss This!