Teaching Kids Programming – Concatenation of Arrays


Teaching Kids Programming: Videos on Data Structures and Algorithms

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]

Hint:
Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]

Concatenate Two Arrays in Python

We can use arr*2 or arr+arr:

1
2
3
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        return nums * 2 # or nums + nums
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        return nums * 2 # or nums + nums

Alternatively, we can append elements to the list – the following clones (deep copy) original array:

1
2
3
4
5
6
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        arr = [i for i in nums] # or copy.deepcopy(nums)
        for i in nums:
            arr.append(i)
        return arr
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        arr = [i for i in nums] # or copy.deepcopy(nums)
        for i in nums:
            arr.append(i)
        return arr

If we want to directly push to the input array:

1
2
3
4
5
6
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        n = len(nums)
        for i in range(n):
            nums.append(nums[i])
        return nums
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        n = len(nums)
        for i in range(n):
            nums.append(nums[i])
        return nums

Alternatively:

1
2
3
4
5
6
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        n = len(nums)
        for i in nums[:n]:
            nums.append(i)
        return nums
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        n = len(nums)
        for i in nums[:n]:
            nums.append(i)
        return nums

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
395 words
Last Post: BASH Function to Check if sudo Available
Next Post: BASH Function to Get Memory Information via AWK

The Permanent URL is: Teaching Kids Programming – Concatenation of Arrays

Leave a Reply