easy

Concatenation of Array

Concatenate an array with itself into one longer array.

1. Define the problem

Concatenation of Array

Given an integer array nums of length n, return an array ans of length 2n where ansi == numsi and ans[i + n] == numsi for every valid index i. In other words, ans is the concatenation of two nums arrays.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 1000
  • 1 ≤ numsi ≤ 1000

Example

Inputnums = [1, 2, 1]
Output[1, 2, 1, 1, 2, 1]

Explanation The array [1, 2, 1] is concatenated with itself to form [1, 2, 1, 1, 2, 1].

2. Know the words first

In plain terms

Concatenation
Joining two sequences end to end to form one longer sequence — here, nums followed immediately by another copy of nums.
3. Visualize the solution

Copy nums, then copy it again right after

Copy nums, then copy it again right after
Statusinit

First pass: copy nums[0]=1 into ans[0].

What happens in this step

ans[0] = nums[0] = 1
ans = [1]
Step 1 of 4

Steps to visualize

  1. Create an empty result array.
  2. Copy every value of nums into the result, in order.
  3. Copy every value of nums into the result again, right after the first copy.
  4. The result now has length 2n, with nums repeated twice.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Copy nums, then copy it again right after
Statusinit

First pass: copy nums[0]=1 into ans[0].

What happens in this step

ans[0] = nums[0] = 1
ans = [1]
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function getConcatenation(nums) {
  const n = nums.length;
  const ans = new Array(2 * n);

  for (let i = 0; i < n; i++) {
    ans[i] = nums[i];
    ans[i + n] = nums[i];
  }

  return ans;
}
Time
O(n)
Space
O(n)
6. Test cases

Test cases

InputExpectedCovers
nums = [1, 2, 1][1, 2, 1, 1, 2, 1]example from the docstring
nums = [7][7, 7]smallest valid input, a single element
nums = [1, 3, 2, 1][1, 3, 2, 1, 1, 3, 2, 1]a slightly longer array with a duplicate value
nums = [4, 4][4, 4, 4, 4]every value identical
nums = [1, 2, 3][1, 2, 3, 1, 2, 3]strictly increasing values
nums = [5, 3, 1][5, 3, 1, 5, 3, 1]strictly decreasing values