Introduction
The Concatenation of Array problem involves creating a new array by appending the original array to itself.
Given an integer array arr[], the task is to create an array:
ans = arr + arrThis means:
- the original array appears twice consecutively
This problem helps in understanding:
- array traversal
- indexing techniques
- array construction
- sequential copying
Example
Input:arr[] = [1,2,1]
Output:
[1,2,1,1,2,1]
Explanation:
Original array is repeated twice.
Input:
arr[] = [1,3,2,1]
Output:
[1,3,2,1,1,3,2,1]
Explanation:
Second copy is appended after first array.
Constraints
1 <= n <= 10001 <= arr[i] <= 1000
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Create a new array
- Traverse original array twice
- Insert elements into result array
This approach is easy to understand and directly follows the problem statement.
Steps
- Create result array.
- Traverse original array first time:
- insert elements
- Traverse original array second time:
- insert elements again
- Return result array.
Dry Run
Input:arr = [1,2,1]
First Traversal:
Add 1
Add 2
Add 1
Result:
[1,2,1]
Second Traversal:
Add 1
Add 2
Add 1
Final Result:
[1,2,1,1,2,1]
Brute Force Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Array is traversed twice.
Space Complexity: O(n)
Explanation:
Extra result array is used.
Approach 2 : Optimized Solution (Direct Index Placement)
Explanation
Instead of traversing twice separately, we can directly place elements into the correct positions using indexing.
The idea is:
- first half stores original array
- second half stores copied array
This provides cleaner placement logic.
Steps
- Create result array of size 2n.
- Traverse original array.
- Place:
- arr[i] at index i
- arr[i] at index i + n
- Return result array.
Dry Run
Input:arr = [1,2,1]
Create result array:
[_,_,_,_,_,_]
Place first 1:
result[0] = 1
result[3] = 1
Result:
[1,_,_,1,_,_]
Place 2:
result[1] = 2
result[4] = 2
Result:
[1,2,_,1,2,_]
Place last 1:
result[2] = 1
result[5] = 1
Final Result:
[1,2,1,1,2,1]
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation: Each element is copied twice.
Space Complexity: O(n)
Explanation:
Extra result array is used.