Find the Array Concatenation Value solution and explanation
9 more videos on this problem
Leetcode | 2562. Find the Array Concatenation Value | Easy | Java SolutionDeveloper Docs · 5:23 · 771 views
2562. Find the Array Concatenation Value | Weekly Contest 332 | LeetCode 2562Bro Coders · 7:00 · 598 views
Find the Array Concatenation Value || LeetCode Weekly Contest 332 || Solution with ExplanationLearn to Code · 5:01 · 516 views
Leetcode : 2562 || Find the Array Concatenation Value || C++ || Weekly Contest 332 @codewithanushaCodeWithAnusha · 7:07 · 475 views
Leetcode Weekly Contest 332 | Find the Array Concatenation Value | PythonBayu Aji · 4:01 · 400 views
Leetcode 2562: Find the Array Concatenation ValueAlgorithms Casts · 3:55 · 224 views
Leetcode 2562 Find the Array Concatenation Value (Java) - Leetcode Weekly Contest 332TheAnalyticGuy · 5:40 · 213 views
2562. Find the Array Concatenation Value (Leetcode Easy)Programming Live with Larry · 3:22 · 193 views
2562. Find the Array Concatenation Value | Leetcode Weekly Contest 332Tech Courses · 4:38 · 121 views
Find the Array Concatenation Value | Leetcode 2562 | Approach + Code with explanation.Pirai's Academy · 13:43 · 92 views
The problem
You are given a 0-indexed integer array nums.
The concatenation of two numbers is the number formed by concatenating their numerals.
- For example, the concatenation of
15,49is1549.
The concatenation value of nums is initially equal to 0. Perform this operation until nums becomes empty:
- If there exists more than one number in
nums, pick the first element and last element innumsrespectively and add the value of their concatenation to the concatenation value ofnums, then delete the first and last element fromnums. - If one element exists, add its value to the concatenation value of
nums, then delete it.
Return the concatenation value of the nums.
Example 1:
Input: nums = [7,52,2,4] Output: 596 Explanation: Before performing any operation, nums is [7,52,2,4] and concatenation value is 0. - In the first operation: We pick the first element, 7, and the last element, 4. Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74. Then we delete them from nums, so nums becomes equal to [52,2]. - In the second operation: We pick the first element, 52, and the last element, 2. Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596. Then we delete them from the nums, so nums becomes empty. Since the concatenation value is 596 so the answer is 596.
Example 2:
Input: nums = [5,14,13,8,12] Output: 673 Explanation: Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0. - In the first operation: We pick the first element, 5, and the last element, 12. Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512. Then we delete them from the nums, so nums becomes equal to [14,13,8]. - In the second operation: We pick the first element, 14, and the last element, 8. Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660. Then we delete them from the nums, so nums becomes equal to [13]. - In the third operation: nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673. Then we delete it from nums, so nums become empty. Since the concatenation value is 673 so the answer is 673.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 104
Approach overview
Problem Overview: You are given an integer array nums. Repeatedly take the first and last elements, concatenate them into a new number, and add it to a running total. If only one element remains, add it directly. Continue until the array is exhausted and return the final sum.
Approach 1: Two-Pointer Approach (O(n) time, O(1) space)
This method processes the array from both ends using two indices. Start with left = 0 and right = n - 1. On each step, concatenate nums[left] and nums[right] by converting to strings or by multiplying the left value by a power of 10 based on the number of digits in the right value. Add the resulting number to the total, then move both pointers inward. When left == right, add that element directly because it cannot form a pair. This technique scans the array once, so the time complexity is O(n) and the algorithm uses O(1) extra space. The logic is a classic application of two pointers on an array, combined with straightforward simulation of the process described in the problem.
The key insight is that the operation only depends on symmetric positions in the array. Instead of modifying the array or repeatedly removing elements, two pointers allow you to simulate the exact behavior while keeping the implementation simple and efficient. Each iteration handles two elements, so the number of operations scales linearly with the array size.
Approach 2: Stack-Based Approach (O(n) time, O(n) space)
A stack can simulate access to the last element while iterating from the front. Push all elements of the array onto a stack, then iterate from the start of the array. For each element, pop the top of the stack to obtain the corresponding last element. Concatenate the two values and add them to the result. Stop when the iteration index crosses the remaining stack size. If the same element would be used twice (middle element in an odd-length array), add it directly instead of concatenating.
This approach also runs in O(n) time because each element is pushed and popped once. However, it requires O(n) extra space for the stack. The implementation is conceptually simple but less space-efficient than the two-pointer method. It can still be useful when practicing stack operations or when the input structure naturally arrives in a streaming order where reverse access is needed.
Recommended for interviews: The two-pointer approach is the expected solution. It achieves O(n) time with O(1) space and directly models the first-and-last pairing described in the problem. Showing the stack version demonstrates understanding of alternative data structures, but the constant-space two-pointer solution highlights stronger algorithmic judgment.
Approach 1: Two-pointer Approach
This approach uses two pointers to track the first and last elements of the array. By incrementing the start pointer and decrementing the end pointer, we efficiently process the array from both ends, concatenating values along the way.
def find_concatenation_value(nums):
total = 0
start, end = 0, len(nums) - 1
while start <= end:
if start == end:
total += nums[start]
start += 1
else:
concat_value = int(str(nums[start]) + str(nums[end]))
total += concat_value
start += 1
end -= 1
return total
nums = [7, 52, 2, 4]
print("Output:", find_concatenation_value(nums))public class Main {
public static int findConcatenationValue(int[] nums) {
int sum = 0;
int start = 0, end = nums.length - 1;
while (start <= end) {
if (start == end) {
sum += nums[start];
start++;
} else {
String concat = Integer.toString(nums[start]) + Integer.toString(nums[end]);
sum += Integer.parseInt(concat);
start++;
end--;
}
}
return sum;
}
public static void main(String[] args) {
int[] nums = {7, 52, 2, 4};
System.out.println("Output: " + findConcatenationValue(nums));
}
}#include <iostream>
#include <string>
using namespace std;
int findConcatenationValue(vector<int>& nums) {
int sum = 0;
int start = 0, end = nums.size() - 1;
while (start <= end) {
if (start == end) {
sum += nums[start];
break;
} else {
string concat = to_string(nums[start]) + to_string(nums[end]);
sum += stoi(concat);
start++;
end--;
}
}
return sum;
}
int main() {
vector<int> nums = {7, 52, 2, 4};
cout << "Output: " << findConcatenationValue(nums) << endl;
return 0;
}function findConcatenationValue(nums) {
let total = 0;
let start = 0, end = nums.length - 1;
while (start <= end) {
if (start === end) {
total += nums[start];
start++;
} else {
let concatValue = parseInt(nums[start].toString() + nums[end].toString(), 10);
total += concatValue;
start++;
end--;
}
}
return total;
}
let nums = [7, 52, 2, 4];
console.log("Output:", findConcatenationValue(nums));#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int findConcatenationValue(int* nums, int numsSize){
int sum = 0;
int start = 0, end = numsSize - 1;
char buffer[20];
while (start <= end) {
if (start == end) {
sum += nums[start];
start++;
} else {
sprintf(buffer, "%d%d", nums[start], nums[end]);
sum += atoi(buffer);
start++;
end--;
}
}
return sum;
}
int main() {
int nums[] = {7, 52, 2, 4};
int size = sizeof(nums) / sizeof(nums[0]);
printf("Output: %d\n", findConcatenationValue(nums, size));
return 0;
}using System;
public class Program
{
public static int FindConcatenationValue(int[] nums)
{
int sum = 0;
int start = 0, end = nums.Length - 1;
while (start <= end)
{
if (start == end)
{
sum += nums[start];
start++;
}
else
{
string concat = nums[start].ToString() + nums[end].ToString();
sum += int.Parse(concat);
start++;
end--;
}
}
return sum;
}
public static void Main()
{
int[] nums = { 7, 52, 2, 4 };
Console.WriteLine("Output: " + FindConcatenationValue(nums));
}
}Python's dynamic typing and string manipulation make it an ideal language for tasks involving frequent number and string conversions, as seen in this solution.
Time Complexity: O(n). Space Complexity: O(1), with minimal use of string space.
Approach 2: Stack-Based Approach
Using a stack to keep track of the numbers effectively simplifies the task of processing from both ends. By pushing numbers onto a stack and then popping them, we manage concatenations seamlessly.
def find_concatenation_value(nums):
stack = nums[:]
total = 0
while stack:
if len(stack) == 1:
total += stack.pop()
else:
start = stack.pop(0)
end = stack.pop(-1)
concat_value = int(str(start) + str(end))
total += concat_value
return total
nums = [7, 52, 2, 4]
print("Output:", find_concatenation_value(nums))import java.util.Stack;
public class Main2 {
public static int findConcatenationValue(int[] nums) {
Stack<Integer> stack = new Stack<>();
for (int num : nums) {
stack.push(num);
}
int sum = 0;
while (!stack.isEmpty()) {
if (stack.size() == 1) {
sum += stack.pop();
} else {
int end = stack.pop();
int start = nums[nums.length - stack.size() - 1];
String concat = start + "" + end;
sum += Integer.parseInt(concat);
}
}
return sum;
}
public static void main(String[] args) {
int[] nums = {7, 52, 2, 4};
System.out.println("Output: " + findConcatenationValue(nums));
}
}#include <iostream>
#include <stack>
#include <string>
using namespace std;
int findConcatenationValue(vector<int>& nums) {
stack<int> s;
for (int num : nums) {
s.push(num);
}
int sum = 0;
while (!s.empty()) {
if (s.size() == 1) {
sum += s.top();
s.pop();
} else {
int end = s.top();
s.pop();
int start = nums[nums.size() - s.size() - 1];
string concat = to_string(start) + to_string(end);
sum += stoi(concat);
}
}
return sum;
}
int main() {
vector<int> nums = {7, 52, 2, 4};
cout << "Output: " << findConcatenationValue(nums) << endl;
return 0;
}function findConcatenationValue(nums) {
let stack = [...nums];
let total = 0;
while (stack.length > 0) {
if (stack.length === 1) {
total += stack.pop();
} else {
let start = stack.shift();
let end = stack.pop();
let concatValue = parseInt(start.toString() + end.toString(), 10);
total += concatValue;
}
}
return total;
}
let nums = [7, 52, 2, 4];
console.log("Output:", findConcatenationValue(nums));#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int findConcatenationValue(int* nums, int numsSize) {
int sum = 0;
int top = -1;
int* stack = (int*)malloc(numsSize * sizeof(int));
for (int i = 0; i < numsSize; ++i) {
stack[++top] = nums[i];
}
while (top >= 0) {
if (top == 0) {
sum += stack[top--];
} else {
char buffer[20];
sprintf(buffer, "%d%d", stack[0], stack[top]);
sum += atoi(buffer);
for (int j = 0; j < top; ++j) {
stack[j] = stack[j + 1];
}
top--;
}
}
free(stack);
return sum;
}
int main() {
int nums[] = {7, 52, 2, 4};
int size = sizeof(nums) / sizeof(nums[0]);
printf("Output: %d\n", findConcatenationValue(nums, size));
return 0;
}using System;
using System.Collections.Generic;
public class Program2
{
public static int FindConcatenationValue(int[] nums)
{
Stack<int> stack = new Stack<int>(nums);
int sum = 0;
for (int i = 0; i < nums.Length; i++)
{
if (stack.Count == 1)
{
sum += stack.Pop();
break;
}
else if (i < stack.Count - 1)
{
int end = stack.Pop();
int start = nums[i];
string concat = start.ToString() + end.ToString();
sum += int.Parse(concat);
}
}
return sum;
}
public static void Main()
{
int[] nums = { 7, 52, 2, 4 };
Console.WriteLine("Output: " + FindConcatenationValue(nums));
}
}Python's list methods allow it to emulate stack-like behavior for both ends, customizable for our needs in pair processing and concatenation.
Time Complexity: O(n^2). Space Complexity: O(n) because of the auxiliary list used as a stack.
Approach 3: Simulation
Starting from both ends of the array, we take out one element at a time, concatenate it with another element, and then add the concatenated result to the answer. We repeat this process until the array is empty.
The time complexity is O(n times log M), and the space complexity is O(log M). Here, n and M are the length of the array and the maximum value in the array, respectively.
function findTheArrayConcVal(nums: number[]): number {
const n = nums.length;
let ans = 0;
let i = 0;
let j = n - 1;
while (i < j) {
ans += Number(`${nums[i]}${nums[j]}`);
i++;
j--;
}
if (i === j) {
ans += nums[i];
}
return ans;
}func findTheArrayConcVal(nums []int) (ans int64) {
i, j := 0, len(nums)-1
for ; i < j; i, j = i+1, j-1 {
x, _ := strconv.Atoi(strconv.Itoa(nums[i]) + strconv.Itoa(nums[j]))
ans += int64(x)
}
if i == j {
ans += int64(nums[i])
}
return
}impl Solution {
pub fn find_the_array_conc_val(nums: Vec<i32>) -> i64 {
let n = nums.len();
let mut ans = 0;
let mut i = 0;
let mut j = n - 1;
while i < j {
ans += format!("{}{}", nums[i], nums[j]).parse::<i64>().unwrap();
i += 1;
j -= 1;
}
if i == j {
ans += nums[i] as i64;
}
ans
}
}Approach 4: Default Approach
impl Solution {
pub fn find_the_array_conc_val(nums: Vec<i32>) -> i64 {
let mut ans = 0;
let mut n = nums.len();
for i in 0..n / 2 {
ans += format!("{}{}", nums[i], nums[n - i - 1])
.parse::<i64>()
.unwrap();
}
if n % 2 != 0 {
ans += nums[n / 2] as i64;
}
ans
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two-pointer Approach | Time Complexity: O(n). Space Complexity: O(1), with minimal use of string space. |
| Stack-Based Approach | Time Complexity: O(n^2). Space Complexity: O(n) because of the auxiliary list used as a stack. |
| Simulation | – |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two-Pointer Approach | O(n) | O(1) | Best general solution. Processes both ends of the array in one pass with constant extra memory. |
| Stack-Based Approach | O(n) | O(n) | Useful when practicing stack operations or when reverse access is easier through a stack. |
Frequently asked questions
Is Find the Array Concatenation Value easy or hard?
LeetCode classifies this problem as Easy. The challenge mainly involves careful handling of two indices and correct concatenation of numbers. Once the two-pointer pattern is recognized, the implementation becomes straightforward.
Find the Array Concatenation Value Python/Java solution
Most implementations use the same logic across languages: two pointers moving toward the center. In Python, Java, C++, or JavaScript, concatenate numbers using string conversion or arithmetic digit shifting, then accumulate the result in a running sum.
How to solve Find the Array Concatenation Value in O(n)?
Use two pointers starting at the first and last indices of the array. Concatenate nums[left] and nums[right] using string conversion or digit multiplication, add the value to the result, and move both pointers inward. If the pointers meet, add the remaining number directly.
What is the best approach for Find the Array Concatenation Value?
The two-pointer approach is the best solution. Place one pointer at the start of the array and another at the end, concatenate their values, add the result to a running sum, and move both pointers inward. This processes each element once and achieves O(n) time with O(1) extra space.
Is Find the Array Concatenation Value asked at Google/Amazon/Meta?
Problems like this commonly appear in interviews at large tech companies because they test array manipulation, pointer techniques, and careful simulation. While the exact question may vary, similar two-pointer and array-processing tasks are frequently asked.
What data structure is used in Find the Array Concatenation Value?
The core data structure is an array. The optimal solution uses the two-pointer technique to access elements from both ends efficiently. An alternative implementation can use a stack to retrieve elements in reverse order.
What is the time complexity of Find the Array Concatenation Value?
The optimal solution runs in O(n) time because each element in the array is processed at most once. Two pointers move toward the center while forming concatenated values. The space complexity is O(1) since only a few variables are required.
