Difficulty: Easy | Acceptance: 90.40% | Paid: No Topics: Array, Simulation
Given an integer array nums, return an array ans where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n, where n is the length of nums. Specifically, ans is the concatenation of two nums arrays.
- Examples
- Constraints
- Simple Iteration
- Built-in Concatenation
- Pre-allocation
Examples
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
Simple Iteration
Intuition Iterate through the input array twice and append each element to the result array.
Steps
- Create an empty result array
- Loop through nums twice
- Append each element to result
python
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
ans = []
for _ in range(2):
for num in nums:
ans.append(num)
return ansComplexity
- Time: O(n)
- Space: O(n)
- Notes: Simple and intuitive approach with clear logic
Built-in Concatenation
Intuition Use language-specific built-in methods to concatenate arrays directly.
Steps
- Use array concatenation operation
- Return the concatenated result
python
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
return nums + numsComplexity
- Time: O(n)
- Space: O(n)
- Notes: Most concise solution using built-in methods
Pre-allocation
Intuition Pre-allocate the result array with the exact required size and fill it in a single pass.
Steps
- Create array of size 2n
- Fill first half with nums
- Fill second half with nums
python
class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [0] * (2 * n)
for i in range(n):
ans[i] = nums[i]
ans[i + n] = nums[i]
return ansComplexity
- Time: O(n)
- Space: O(n)
- Notes: Efficient memory allocation with single loop iteration