Facebook Pixel

1929. Concatenation of Array

EasyArraySimulation
Leetcode Link

Problem Description

You are given an integer array nums of length n. Your task is to create a new array ans of length 2n that is formed by concatenating the array nums with itself.

The concatenation means that:

  • The first n elements of ans are the same as nums: ans[i] == nums[i] for 0 <= i < n
  • The next n elements of ans are again the same as nums: ans[i + n] == nums[i] for 0 <= i < n

In other words, you need to create an array that contains all elements of nums followed by all elements of nums again.

For example:

  • If nums = [1, 2, 3], then ans = [1, 2, 3, 1, 2, 3]
  • If nums = [1, 3, 2, 1], then ans = [1, 3, 2, 1, 1, 3, 2, 1]

The solution is straightforward - in Python, you can simply concatenate the list with itself using the + operator: return nums + nums. This creates a new list containing all elements of nums twice in sequence.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

When we read the problem, we notice that we need to create an array that is exactly twice the length of the original array, where the second half is an exact copy of the first half.

The key observation is that this is literally asking us to concatenate the array with itself. We don't need to manipulate individual elements or perform any transformations - we simply need to place one copy of nums after another.

Since the problem explicitly states that ans[i] == nums[i] for the first n positions and ans[i + n] == nums[i] for the next n positions, we recognize this pattern as array concatenation. The second half starting at index n contains the same elements as nums starting from index 0.

In Python, list concatenation is a built-in operation. When we use nums + nums, Python creates a new list containing all elements from the first nums followed by all elements from the second nums. This directly gives us the desired result without needing to iterate through elements or manually copy values.

The elegance of this solution comes from recognizing that the problem is asking for the most basic form of array concatenation - joining an array with itself. No complex logic or element manipulation is required.

Solution Approach

The solution follows a direct simulation approach as described in the reference. We implement exactly what the problem asks for - creating an array that contains nums concatenated with itself.

Implementation Steps:

  1. Direct Concatenation: The solution uses Python's list concatenation operator + to join nums with itself.

    • When we write nums + nums, Python creates a new list
    • The new list first contains all elements from the first nums
    • Then it appends all elements from the second nums
  2. How the concatenation works internally:

    • For an array nums = [a, b, c] of length n = 3
    • nums + nums produces [a, b, c, a, b, c] of length 2n = 6
    • This satisfies the requirement where:
      • ans[0] = a = nums[0]
      • ans[1] = b = nums[1]
      • ans[2] = c = nums[2]
      • ans[3] = a = nums[0] (which is ans[0 + 3] = nums[0])
      • ans[4] = b = nums[1] (which is ans[1 + 3] = nums[1])
      • ans[5] = c = nums[2] (which is ans[2 + 3] = nums[2])
  3. Time and Space Complexity:

    • Time Complexity: O(n) where n is the length of the input array, as we need to copy all elements twice
    • Space Complexity: O(n) for the output array (which has 2n elements)

The beauty of this solution lies in its simplicity - instead of manually iterating and copying elements, we leverage Python's built-in list concatenation to achieve the desired result in a single, readable line of code.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a concrete example with nums = [5, 7, 2].

Step 1: Understanding the requirement

  • Input array: nums = [5, 7, 2] with length n = 3
  • We need to create an array of length 2n = 6
  • The result should be the original array repeated twice

Step 2: Visualizing the concatenation

Original array:  [5, 7, 2]
                  ↓  ↓  ↓
Position:        0  1  2

Result array:    [5, 7, 2, 5, 7, 2]
                  ↓  ↓  ↓  ↓  ↓  ↓
Position:        0  1  2  3  4  5

Step 3: Applying the solution When we execute nums + nums:

  • Python takes the first nums: [5, 7, 2]
  • Then appends the second nums: [5, 7, 2]
  • Creates a new list: [5, 7, 2, 5, 7, 2]

Step 4: Verifying the constraints Let's check that our result satisfies the problem requirements:

  • First half (indices 0-2): ans[0]=5, ans[1]=7, ans[2]=2 ✓ matches nums
  • Second half (indices 3-5): ans[3]=5, ans[4]=7, ans[5]=2 ✓ matches nums
  • We can also verify: ans[i+n] == nums[i] for all valid i:
    • ans[0+3]=ans[3]=5 equals nums[0]=5
    • ans[1+3]=ans[4]=7 equals nums[1]=7
    • ans[2+3]=ans[5]=2 equals nums[2]=2

The final result [5, 7, 2, 5, 7, 2] is exactly what we need - the original array concatenated with itself.

Solution Implementation

1class Solution:
2    def getConcatenation(self, nums: List[int]) -> List[int]:
3        """
4        Returns a new array that is the concatenation of nums with itself.
5      
6        Args:
7            nums: A list of integers to be concatenated
8          
9        Returns:
10            A list containing nums followed by nums again (nums concatenated twice)
11        """
12        # Concatenate the array with itself using list addition
13        # This creates a new list with all elements of nums appearing twice in order
14        return nums + nums
15
1class Solution {
2    /**
3     * Creates a concatenated array where the original array is repeated twice.
4     * Given an array nums of length n, returns a new array of length 2n where
5     * ans[i] = nums[i] for 0 <= i < n and ans[i] = nums[i - n] for n <= i < 2n.
6     * 
7     * @param nums the input array to be concatenated
8     * @return a new array containing two copies of the input array concatenated together
9     */
10    public int[] getConcatenation(int[] nums) {
11        // Store the length of the input array
12        int length = nums.length;
13      
14        // Create result array with double the size of input array
15        int[] result = new int[length * 2];
16      
17        // Iterate through all positions in the result array
18        for (int i = 0; i < length * 2; i++) {
19            // Use modulo operator to map indices:
20            // - When i < length: i % length = i (first copy)
21            // - When i >= length: i % length = i - length (second copy)
22            result[i] = nums[i % length];
23        }
24      
25        return result;
26    }
27}
28
1class Solution {
2public:
3    vector<int> getConcatenation(vector<int>& nums) {
4        // Store the original size of the input array
5        int originalSize = nums.size();
6      
7        // Iterate through each element in the original array
8        // and append it to the end of the array
9        for (int i = 0; i < originalSize; ++i) {
10            nums.push_back(nums[i]);
11        }
12      
13        // Return the concatenated array (original + copy)
14        return nums;
15    }
16};
17
1/**
2 * Creates a concatenation of the input array with itself.
3 * The resulting array contains all elements of the original array followed by all elements again.
4 * 
5 * @param nums - The input array of numbers to be concatenated with itself
6 * @returns A new array that is the concatenation of nums with itself
7 * 
8 * Time Complexity: O(n) where n is the length of the input array
9 * Space Complexity: O(n) for the output array
10 * 
11 * Example:
12 * Input: [1, 2, 3]
13 * Output: [1, 2, 3, 1, 2, 3]
14 */
15function getConcatenation(nums: number[]): number[] {
16    // Use spread operator to create a new array containing nums twice
17    return [...nums, ...nums];
18}
19

Time and Space Complexity

The time complexity is O(n), where n is the length of the array nums. The concatenation operation nums + nums in Python creates a new list by iterating through all elements of the first nums array and then all elements of the second nums array, resulting in 2n operations, which simplifies to O(n).

The space complexity is O(n), where n is the length of the array nums. The operation creates a new list that contains exactly 2n elements (the original array concatenated with itself), which requires O(2n) space. This simplifies to O(n) in Big O notation.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Modifying the Original Array Instead of Creating a New One

A common mistake is trying to modify the original array in-place, which can lead to unexpected behavior:

Incorrect Approach:

def getConcatenation(self, nums: List[int]) -> List[int]:
    nums.extend(nums)  # This modifies the original array!
    return nums

Why it's problematic:

  • extend() modifies the original list in-place
  • This can cause issues if the original array is needed elsewhere
  • In some cases, it might even cause infinite loops if not handled carefully

Correct Solution: Always create a new array using concatenation:

def getConcatenation(self, nums: List[int]) -> List[int]:
    return nums + nums  # Creates a new list

2. Using Multiplication Operator Incorrectly

Some might try using the multiplication operator * but misunderstand how it works:

Incorrect Understanding:

def getConcatenation(self, nums: List[int]) -> List[int]:
    return nums * 2  # This works but might be misunderstood

Potential Confusion:

  • While nums * 2 produces the correct result, beginners might think it multiplies each element by 2
  • For clarity, nums + nums is more explicit about concatenation
  • Both approaches have the same time complexity, but + is more intuitive for concatenation

3. Manual Loop Implementation Errors

When implementing manually with loops, off-by-one errors are common:

Error-Prone Approach:

def getConcatenation(self, nums: List[int]) -> List[int]:
    ans = []
    for i in range(2 * len(nums)):
        ans.append(nums[i])  # IndexError when i >= len(nums)!
    return ans

Correct Manual Implementation:

def getConcatenation(self, nums: List[int]) -> List[int]:
    ans = []
    for i in range(2 * len(nums)):
        ans.append(nums[i % len(nums)])  # Use modulo to wrap around
    return ans

4. Assuming Reference Copying

Trying to create the result by reference can lead to issues:

Incorrect Approach:

def getConcatenation(self, nums: List[int]) -> List[int]:
    ans = [nums, nums]  # Creates nested lists, not concatenation!
    return ans  # Returns [[1,2,3], [1,2,3]] instead of [1,2,3,1,2,3]

Best Practice: Stick with the simple and clear nums + nums approach, which correctly creates a flat, concatenated list without any reference issues or complexity.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

How many ways can you arrange the three letters A, B and C?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More