Concatenation of Array easy

Problem Statement

Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n. Return the array ans.

Example 1:

Input: nums = [1,2,1] Output: [1,2,1,1,2,1] Explanation: The final array consists of the original array twice.

Example 2:

Input: nums = [1,3,2,1] Output: [1,3,2,1,1,3,2,1] Explanation: The final array consists of the original array twice.

Steps:

  1. Determine the size of the output array: The output array ans will have twice the length of the input array nums.
  2. Create the output array: Initialize an array ans of size 2 * nums.size().
  3. Copy the input array: Copy the elements of nums into the first half of ans.
  4. Copy the input array again: Copy the elements of nums into the second half of ans.
  5. Return the output array: Return the array ans.

Explanation:

The problem requires creating a new array that contains the original array's elements concatenated with itself. The solution directly implements this concatenation using simple array copying. We allocate an array twice the size of the input, then copy the input array's contents into the first half, and then copy it again into the second half.

Code:

#include <vector>

class Solution {
public:
    std::vector<int> getConcatenation(std::vector<int>& nums) {
        int n = nums.size();
        std::vector<int> ans(2 * n); // Create an array of size 2n

        // Copy nums into the first half of ans
        for (int i = 0; i < n; ++i) {
            ans[i] = nums[i];
        }

        // Copy nums into the second half of ans
        for (int i = 0; i < n; ++i) {
            ans[i + n] = nums[i];
        }

        return ans;
    }
};

Complexity:

  • Time Complexity: O(n), where n is the length of the input array. We iterate through the input array twice.
  • Space Complexity: O(n), as we create a new array of size 2n to store the result.