Concatenation of Array easy

Problem Statement

Given an integer array nums of length n, return an array of length 2n where the array contains all the elements from nums followed by all the elements from nums again.

Example 1:

Input: nums = [1,2,1] Output: [1,2,1,1,2,1] Explanation: The array is [1,2,1]. The concatenated array will be [1,2,1,1,2,1].

Example 2:

Input: nums = [1,3,2,1] Output: [1,3,2,1,1,3,2,1] Explanation: The array is [1,3,2,1]. The concatenated array will be [1,3,2,1,1,3,2,1].

Steps:

  1. Create a result array: Initialize a new array result with a length twice the length of the input array nums.
  2. Copy the input array: Copy all elements from nums into the first half of result.
  3. Copy again: Copy all elements from nums again into the second half of result.
  4. Return the result: Return the result array.

Explanation:

The problem requires simple array manipulation. We create a new array that is double the size of the input array. Then, we populate this new array by copying the contents of the input array twice. This effectively concatenates the input array with itself. The process is straightforward and can be efficiently implemented using array copying techniques.

Code (Java):

class Solution {
    public int[] getConcatenation(int[] nums) {
        int n = nums.length;
        int[] ans = new int[2 * n]; // Create a new array of double the size

        // Copy nums into the first half of ans
        System.arraycopy(nums, 0, ans, 0, n);

        // Copy nums into the second half of ans
        System.arraycopy(nums, 0, ans, n, n);

        return ans;
    }
}

Complexity:

  • Time Complexity: O(n), where n is the length of the input array. This is because we iterate through the input array a constant number of times (twice) during the copying process. System.arraycopy has a time complexity of O(n).
  • Space Complexity: O(n). We create a new array of size 2n to store the result. Therefore, the space used is directly proportional to the size of the input array.