Find the Array Concatenation Value Solution in C++

Language Options

Java Solution |
Python Solution

Problem Description

Welcome to the whimsical world of array concatenation! Imagine you have a group of numbers, and you want to create a new number by concatenating them in a specific way. Sounds simple, right? Well, hold onto your hats because this is not just any ordinary concatenation!

In the problem “Find the Array Concatenation Value,” you are tasked with taking an array of integers and creating a single number by concatenating the first half of the array with the reversed second half. For example, if you have an array like [1, 2, 3, 4], you would take 1 and 2, and concatenate them with 4 and 3 to get 1234. Easy peasy, lemon squeezy! But wait, what if the array has an odd number of elements? Well, then you just have to be a little more creative!

Code Solution


class Solution {
 public:
  long long findTheArrayConcVal(vector& nums) {
    long ans = 0;

    for (int i = 0, j = nums.size() - 1; i <= j; ++i, --j) {
      ans += nums[j];
      if (i < j)
        ans += nums[i] * pow(10, static_cast(log10(nums[j])) + 1);
    }

    return ans;
  }
};

Approach Explanation

The code works by using two pointers: one starting from the beginning of the array (i) and the other from the end (j). It adds the number at the end to the result and, if the pointers haven’t crossed, it concatenates the number at the beginning by multiplying it by a power of 10 that corresponds to the number of digits in the number at the end. This way, you create the desired concatenated value without breaking a sweat!

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the number of elements in the array. We traverse the array once.
Space Complexity O(1), as we are using a constant amount of space for the variables.

Real-World Example

Imagine you’re at a party, and you have a list of guests. You want to create a unique party ID by combining the first half of the guests with the last half in reverse order. If you have guests named “Alice,” “Bob,” “Charlie,” and “Diana,” your party ID would be “AliceDianaBobCharlie.” This is exactly what the problem is asking you to do with numbers!

Similar Problems

If you enjoyed this problem, you might also like these: