Concatenation of Array

(#1929), Easy

Category: Array

Problem Statement

You're given an integer array nums of length n. Your task is to create a new array ans of length 2n, such that: ans[i] = nums[i] ans[i + n] = nums[i] for all 0 <= i < n. In simpler terms, return the concatenation of the array with itself.

Examples

Input: nums = [1, 2, 1]

Output: [1, 2, 1, 1, 2, 1]

Explanation: Concatenate the input array with itself: [1, 2, 1] + [1, 2, 1] = [1, 2, 1, 1, 2, 1].

Approach

Using a For Loop

  • Initialize an empty array `ans`.
  • Store the length of the array `nums` as `n`.
  • Loop from `i = 0` to `n - 1`.
  • At each step, set `ans[i] = nums[i]` and `ans[i + n] = nums[i]`.
  • Return `ans`.
var getConcatenation = function(nums) {
    let ans = [];
    let n = nums.length;

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

    return ans;
};

Using Spread Operator (One-liner)

  • Use the spread operator to duplicate the array.
  • Return a new array: `[...nums, ...nums]`.
var getConcatenation = function(nums) {
    return [...nums, ...nums];
};

Complexity

Time: O(n)

Space: O(n)

Watch Explanation

📎 Resources