Concatenation of Array(#1929)

Category: Array, Foundation

๐Ÿงฉ 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

Approach 1: Using a For Loop

โ€ข Initialize an empty array `ans`.

โ€ข Loop through `nums`, and for each element, add it at index `i` and `i + n`.

โ€ข Return `ans`.

Approach 2: Using Spread Operator

โ€ข Return `[...nums, ...nums]` which duplicates and concatenates the array.

Both solutions run in O(n) time and are very beginner-friendly.

๐Ÿ’ป Code

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;
};

// One-liner approach:
var getConcatenation = function(nums) {
     return [...nums, ...nums];
};

๐Ÿ“ˆ Complexity

Time: O(n)

Space: O(n)

๐ŸŽฌ Watch Explanation

๐Ÿ“Ž Resources