Back to solutions

Concatenation of Array

EasyArrays

Return the array concatenated with itself.

Constraints
  • 1 <= n <= 1000
  • 1 <= nums[i] <= 1000

Copy twice

Time O(n)Space O(n)

Build a result of size 2n and fill it by writing each value at index i and again at index i+n. A single pass over the input is enough.

Key terms
concatenation:
Joining two sequences end to end into one longer sequence.
vector<int> getConcatenation(vector<int>& nums) {
    vector<int> ans(nums);
    ans.insert(ans.end(), nums.begin(), nums.end());
    return ans;
}
Step by step
  1. Allocate ans with room for 2n elements.
  2. For each i, set ans[i] = nums[i] and ans[i + n] = nums[i].
  3. Return ans.