Find the Array Concatenation Value — Easy Problem & Solution

The concatenation of two integers is the number formed by writing the first and then the second, so concatenating 15 and 49 gives 1549.

  • Difficulty: Easy
  • Topics: Arrays, Two Pointers, Simulation
  • Asked at: TCS, Mindtree
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

The concatenation of two integers is the number formed by writing the first and then the second, so concatenating 15 and 49 gives 1549.

Repeat until nums is empty: if at least two elements remain, remove the first and last, concatenate them in that order and add the result to a running total; if exactly one element remains, add it to the total and remove it.

Return the total.

Example 1

Input: nums = [7,52,2,4]
Output: 596
Explanation: 7 and 4 concatenate to 74; then 52 and 2 concatenate to 522. 74 + 522 = 596.

Example 2

Input: nums = [5,14,13,8,12]
Output: 673
Explanation: 512 + 148 + 13 = 673 — 13 is the lone middle element.

Example 3

Input: nums = [9]
Output: 9

Constraints

  • 1 <= nums.length <= 30
  • 1 <= nums[i] <= 999

How to solve Find the Array Concatenation Value

Removing the first and last element repeatedly is exactly a two-pointer walk inward, so nothing needs to be deleted from the array at all.

Approach

  1. Set i = 0 and j = n - 1.
  2. While i < j, add the concatenation of nums[i] and nums[j] to the total, then step i forward and j back.
  3. If i == j after the loop, one element is left — add it as it is.

Why it works

Each iteration consumes exactly the pair the statement removes, in the same order, so the running total matches the simulation step for step. The loop ends when fewer than two elements remain, which is precisely when the single-element rule applies.

Complexity

  • Time — O(n · d) where d is the digit count
  • Space — O(1)

Pitfalls

  • Concatenating in the wrong order — it is first-then-last, not last-then-first.
  • Forgetting the lone middle element in an odd-length array.

Reference solution

Python

from typing import List

def findTheArrayConcVal(nums: List[int]) -> int:
    i, j = 0, len(nums) - 1
    total = 0
    while i < j:
        total += int(str(nums[i]) + str(nums[j]))
        i += 1
        j -= 1
    if i == j:
        total += nums[i]
    return total

JavaScript

var findTheArrayConcVal = function(nums) {
    var i = 0, j = nums.length - 1, total = 0;
    while (i < j) {
        total += Number(String(nums[i]) + String(nums[j]));
        i++;
        j--;
    }
    if (i === j) total += nums[i];
    return total;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue