Concatenation of Array

Solution 1

This solution builds the concatenated array by iterating through the input twice and appending its elements to a new list in each pass.

Pseudocode

  1. Initialize an empty list, ans.
  2. Iterate through the input list nums once, appending each element to ans.
  3. Iterate through nums a second time, again appending each element to ans.
  4. Return the list ans, which now contains two copies of the original nums list.

Code

class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        result = []
        for n in nums:
            result.append(n)
        for n in nums:
            result.append(n)
        return result

Complexity Analysis

Tricks

  1. Pythonic Concatenation: The most common and readable trick in Python for this problem is using the + operator, which is overloaded for lists. The entire function can be a single line: return nums + nums.
  2. List Multiplication: An even more concise trick is to use the * operator to repeat the list's elements. This is also a one-liner: return nums * 2. It's a powerful feature for creating lists with repeated patterns.

Solution 2

This solution pre-allocates an array of double the original size and then fills both the first and second halves in a single pass.

Pseudocode

  1. Get the length of the input array nums and store it as n.
  2. Create a new array ans with a size of 2 * n, initialized with placeholder values.
  3. Iterate through the original nums array using both the index i and value n.
  4. In each iteration, place the value n into two positions in the ans array: at index i and at index i + n.
  5. Return the ans array.

Code

class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        length = len(nums)
        result = [0] * (2 * length)
        for i, n in enumerate(nums):
            result[i] = result[i + length] = n
        return result

Complexity Analysis

Tricks

  1. Pre-allocation for Efficiency: Initializing the list to its final size (result = [0] * (2 * length)) is often more performant than dynamically growing the list with append(), as it avoids potential memory reallocations.
  2. Single-Pass Logic: The core trick is filling both halves of the new array in one loop. The assignment result[i] = result[i + length] = n is a clever, compact way to place the current number in its correct position in both the first and second copy.
  3. Using enumerate: enumerate is a clean, Pythonic way to get both the index and value of an item while iterating, which is perfect for this kind of index-based assignment.