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
- Initialize an empty list,
ans. - Iterate through the input list
numsonce, appending each element toans. - Iterate through
numsa second time, again appending each element toans. - Return the list
ans, which now contains two copies of the originalnumslist.
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
- Time Complexity:
, where is the number of elements in nums. The code iterates through the input list twice, which isoperations, simplifying to . - Space Complexity:
, because a new list of size is created to store the result.
Tricks
- 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. - 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
- Get the length of the input array
numsand store it asn. - Create a new array
answith a size of2 * n, initialized with placeholder values. - Iterate through the original
numsarray using both the indexiand valuen. - In each iteration, place the value
ninto two positions in theansarray: at indexiand at indexi + n. - Return the
ansarray.
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
- Time Complexity:
, where is the length of nums. We perform a single loop through the input array. - Space Complexity:
, as we allocate a new array of size to store the result.
Tricks
- Pre-allocation for Efficiency: Initializing the list to its final size (
result = [0] * (2 * length)) is often more performant than dynamically growing the list withappend(), as it avoids potential memory reallocations. - Single-Pass Logic: The core trick is filling both halves of the new array in one loop. The assignment
result[i] = result[i + length] = nis a clever, compact way to place the current number in its correct position in both the first and second copy. - Using
enumerate:enumerateis 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.