Concatenation of Array

Build an array that holds the input array twice in a row, by writing each value to two positions.

You are given an integer array nums of length n. Return a new array ans of length 2n that holds nums twice, one copy right after the other. Put another way, ans[i] and ans[i + n] both equal nums[i], for every index i from 0 to n - 1.

Example 1
Input: nums = [1, 2, 1]
Output: [1, 2, 1, 1, 2, 1]
Example 2
Input: nums = [1, 3, 2, 1]
Output: [1, 3, 2, 1, 1, 3, 2, 1]
Solution

The Idea

Think of a playlist of three songs set to play through twice. The order you hear is the list, then the same list again. Joining two lists end to end like this is called concatenation, and here an array is joined to itself.

Take Example 1, nums = [1, 2, 1], so n is 3. The answer has six places, numbered 0 to 5. Places 0, 1 and 2 hold the first copy, and places 3, 4 and 5 hold the second. So where does one value of nums end up in ans?

Look at the picture below. The 2 sits at index 1 of nums. In ans it appears at index 1, in the first copy, and again at index 4, in the second copy.

nums = [1, 2, 1] has n = 3. In ans, which is twice as long, the 2 at index 1 of nums is written to index 1, in the first copy, and to index 1 + 3 = 4, in the second copy.

Why 4? The second copy starts after the whole first copy, which is n = 3 places long. So every value moves exactly 3 places further along: index 1 becomes 1 + 3 = 4. The two 1s follow the same rule, from index 0 to indexes 0 and 3, and from index 2 to indexes 2 and 5.

So each value of nums has two known homes in ans: index i and index i + n. One pass over nums can fill both.

Solution Approach

Turning that idea into code means settling two things: which array the loop walks over, and whether to write the copy by hand or let Java's library do it.

Walking over nums, not over ans

Which loop is simplest? One that runs over the n indexes of nums and makes two writes each time, to ans[i] and to ans[i + n]. Every read of nums[i] is then in range, and both halves fill at the same time.

A loop over all 2n places of ans works too, but it cannot read nums[i] directly. For [1, 2, 1], reading nums[3] throws an ArrayIndexOutOfBoundsException, Java's error for an index past the end of an array. That loop has to read nums[i % n] instead, where % is the remainder: 3 % 3 is 0, 4 % 3 is 1, so the indexes wrap back to the start.

Copying with System.arraycopy

Is there a ready-made way? System.arraycopy(src, srcPos, dest, destPos, length) copies length values from one array into another. Called twice, with destPos set to 0 and then to n, it fills both copies. It gives the same result and is a good choice in everyday code. Here we still write the loop, because it keeps the index arithmetic in plain sight.

Java Solution

The method getConcatenation works in these steps:

  1. First, store the length of nums in n, and create the result array ans with new int[2 * n]. Java fills a new int array with zeros, and every one of them will be overwritten.
  2. Then a loop moves i from 0 to n - 1. Each time, it writes nums[i] to ans[i] for the first copy, and to ans[i + n] for the second copy.
  3. When the loop is done, return ans.

The main method runs both examples, a single value, an empty array, and a check that changing the result leaves the input as it was.

Java
import java.util.Arrays;

public class ConcatenationOfArray {

    public static int[] getConcatenation(int[] nums) {
        int n = nums.length;
        int[] ans = new int[2 * n];
        for (int i = 0; i < n; i++) {
            ans[i] = nums[i];                 // first copy
            ans[i + n] = nums[i];             // second copy, n places later
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(getConcatenation(new int[] {1, 2, 1})));
        System.out.println(Arrays.toString(getConcatenation(new int[] {1, 3, 2, 1})));
        System.out.println(Arrays.toString(getConcatenation(new int[] {5})));
        System.out.println(Arrays.toString(getConcatenation(new int[] {})));
        int[] nums = {7, 8, 9};
        int[] ans = getConcatenation(nums);
        ans[0] = 100;
        System.out.println(Arrays.toString(nums) + " " + Arrays.toString(ans));
    }
}

Running it prints:

Output
[1, 2, 1, 1, 2, 1]
[1, 3, 2, 1, 1, 3, 2, 1]
[5, 5]
[]
[7, 8, 9] [100, 8, 9, 7, 8, 9]

The answers [1, 2, 1, 1, 2, 1] and [1, 3, 2, 1, 1, 3, 2, 1] match the two examples. A single value, [5], simply comes out twice as [5, 5]. For the empty array, n is 0, so ans has length 0, the loop never runs, and [] comes back without an error.

Look at the last line. The program set ans[0] to 100, and nums still prints [7, 8, 9]. The values were copied into a new array, so the caller's array is never touched.

The original implementation, ConcatenationOfArray.java, is on GitHub.

Complexity

The work is creating an array of 2n places and one pass over nums.

  • Time: O(n), where n is the length of nums. The loop runs n times with two writes each, and creating the array of 2n zeros also takes time in proportion to n.
  • Space: O(n) for the result. ans holds 2n values. Apart from it, the method keeps only n and the loop index.

Treating index i + n as holding the same value as index i also helps with circular arrays, where the end wraps around to the start, as in Maximum Sum Circular Subarray.