We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Concatenation of Array

Number: 2058

Difficulty: Easy

Paid? No

Companies: Google, Bloomberg, Meta, Amazon, Microsoft, GE Healthcare


Problem Description

Given an integer array nums of length n, form an array ans of length 2n by concatenating nums with itself, such that ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n.


Key Insights

  • The problem is essentially about duplicating the array by concatenating it with itself.
  • A new array of size 2n needs to be created.
  • The solution involves a simple copy of elements, first copying the original array, then copying it again.
  • The use of simple array operations ensures clarity and efficiency.

Space and Time Complexity

Time Complexity: O(n) where n is the number of elements in nums. Space Complexity: O(n) for the additional array of size 2n (ignoring output space, the extra space is linear with respect to n).


Solution

The approach is straightforward:

  1. Create a new array, ans, of length 2n (or, in high-level languages, you can simply append/catenate the array with itself).
  2. Iterate over the original array and copy each element to the corresponding position in ans.
  3. During the same or a separate iteration, copy the original array again so that the first copy is placed at the beginning and the second copy starts at index n.
  4. Return the final array ans.

This method leverages simple array traversal and copying, ensuring clarity and optimal performance.


Code Solutions

# Define the function that performs the concatenation
def get_concatenation(nums):
    # Create the resultant array by concatenating nums with itself
    result = nums + nums
    # Return the concatenated array
    return result

# Example usage
if __name__ == "__main__":
    nums = [1, 2, 1]
    # Expected output: [1, 2, 1, 1, 2, 1]
    print(get_concatenation(nums))
← Back to All Questions