Taro Logo

Concatenation of Array

#134 Most AskedEasy
Topics:
Arrays

Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Return the array ans.

Example 1:

Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [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 ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]

Constraints:

  • n == nums.length
  • 1 <= n <= 1000
  • 1 <= nums[i] <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the input array `nums` (i.e., what is the range for $n$)?
  2. Can the input array `nums` be empty, and if so, should the output be an empty array?
  3. What types of integers are contained within the array? Are we dealing with standard 32-bit signed integers, and could they be negative or zero?
  4. Should the result be returned as a brand-new array in memory, or is it expected to be constructed in-place if the target language allows?
  5. Are there any memory allocation limits or specific language-idiomatic return types we should adhere to?

Brute Force Solution

Approach

Imagine you have a row of items and need to create a brand new row that contains the exact same items followed by a duplicate copy of those same items. The brute force approach achieves this by physically gathering a fresh collection and copying everything over twice from the original.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item in your original collection.
  2. Pick up that item and place a copy of it into your new collection.
  3. Move along the original collection one item at a time, copying each one over to the new collection until you reach the end.
  4. Once you have copied the entire original collection once, go back to the very beginning of the original collection.
  5. Start copying all the items a second time, placing them right behind the ones you just finished placing.
  6. Continue this process until every single item from the original collection has been copied over a second time.
  7. Present the completed new collection as your final result.

Code Implementation

def get_concatenation(original_array):
    # Allocate space for twice the items to fit both copies sequentially without resizing
    result_array = [0] * (len(original_array) * 2)

    # Iterate through the original items twice to populate the first and second halves
    for current_index in range(len(original_array) * 2):

        # Map the doubled index back to the original array bounds using modulo arithmetic
        source_index = current_index % len(original_array)

        result_array[current_index] = original_array[source_index]

    return result_array

Big(O) Analysis

Time Complexity
O(n) – Letting n represent the number of items in the original collection, the algorithm iterates through all n elements to copy them into the new collection during the first pass. It then iterates through the original collection a second time, taking another n steps to append the duplicate copy. Combining these two sequential passes results in roughly 2n total operations. Since constants are dropped in asymptotic analysis, the overall time complexity simplifies to O(n).
Space Complexity
O(N) – To satisfy the requirement of producing a brand new collection, the algorithm allocates an entirely separate output array of size 2N to hold the duplicated elements. As described in the steps, every item from the original collection of size N is copied over twice into this newly gathered structure. The input itself takes up N space, but the extra memory required for the final result scales directly in proportion to the input size N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To double a line of items efficiently, the best strategy is to create a fresh container that is twice as long as the original. You then simply copy the entire original group of items into the first half of the new container, and then copy the exact same group a second time right into the remaining empty half.

Here's how the algorithm would work step-by-step:

  1. Obtain a brand new container with a total capacity exactly twice as large as the original group of items.
  2. Take the entire collection of items from the original group and place them into the first half of the new container, keeping their original order.
  3. Take that exact same collection of items once more and place them directly into the second half of the new container, right after the first set.
  4. Deliver the newly filled container as the final result.

Code Implementation

class Solution:
    def get_concatenation(self, input_array: list[int]) -> list[int]:
        # We need a new container twice the size to hold the original elements twice.
        original_length = len(input_array)
        
        new_container = [0] * (original_length * 2)
        
        # Copying elements twice ensures the array is successfully concatenated.
        for index in range(original_length):
            new_container[index] = input_array[index]
            new_container[index + original_length] = input_array[index]
            
        return new_container

Big(O) Analysis

Time Complexity
O(n) – Letting n represent the number of items in the original array, the cost is driven by allocating a new container of size 2n and performing two separate copy operations. The first copy operation iterates through all n original items to fill the first half of the new container, taking linear time. The second copy operation iterates through the same n items again to fill the second half of the new container, also taking linear time. Adding these together yields approximately 2n total operations, which simplifies in Big O notation to O(n).
Space Complexity
O(n) – To satisfy the requirement of returning the doubled collection, the algorithm must allocate a brand new output array of size 2n. Because this newly created container exists strictly to hold the duplicated elements and is independent of the input reference, it constitutes our extra memory. Letting n represent the number of elements in the original input group, the space required by this fresh container scales in direct proportion to n. When we simplify this linear growth relationship using asymptotic analysis, the resulting auxiliary space complexity is O(n).

Edge Cases

Empty array input where n equals 0
How to Handle:
The algorithm should allocate an empty array of length zero and return it safely.
Single element array where n equals 1
How to Handle:
The allocation creates a new array of length 2 and populates both indices with the single element.
Maximum allowed array length reaching memory limits
How to Handle:
The solution must efficiently allocate a contiguous block of memory of size 2n without excessive overhead.
Array containing negative numbers and zeros
How to Handle:
Value types do not affect structural concatenation, so elements are copied directly regardless of their sign.
Array with all identical elements
How to Handle:
Duplicating the array simply repeats the same value seamlessly across the first and second halves.
Memory allocation failure due to very large input sizes
How to Handle:
The system will throw an out-of-memory exception if the resulting array exceeds available heap space.
Language-specific primitive type overflow during sizing
How to Handle:
Computing the new length as 2n must use standard integer types that comfortably fit within valid array bounds.
Read-only or immutable input array structures
How to Handle:
Since we only read from the input and build a brand new array, immutability of the source is fully preserved.
0/245 completed