</>

1929. Concatenation of Array

Easy
Arrays & Hashing Time O(N) Space O(N)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Arrays & Hashing
Time
O(N)
Space
O(N)

Standard Solution (C++)

SummaryGiven an integer array, build a new array of double the length by appending the original array to itself, then return the result.

Approach
  • Allocate a result vector of size 2n upfront to avoid reallocations.
  • Copy the input array into the first half, then again into the second half using index arithmetic.
  • This works because each element nums[i] simply appears at positions i and i + n in the output.
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
        int n = nums.size();
        vector<int> ans(2 * n);
        for (int i = 0; i < n; ++i) {
            ans[i]     = nums[i];   // first copy
            ans[i + n] = nums[i];   // second copy, shifted by n
        }
        return ans;
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
        /* Method 1: consider cache locality

        // 1. get the len of the nums
        // 2. init a vector with size len*2
        // 3. fill the 0 ~ len*2
        
        int len=nums.size();
        vector<int> res(len*2, 0);

        for(int i=0; i<len; ++i){
            res[i]=nums[i];
        }
        for(int i=0; i<len; ++i){
            res[i+len]=nums[i];
        }
        return res;

        */

        /* Method 2: standard library */
        vector<int> res;
        res.reserve(nums.size()*2);
        res.insert(res.end(), nums.begin(), nums.end());
        res.insert(res.end(), nums.begin(), nums.end());

        return res;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(N)
Time O(N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern