3925. Concatenate Array With Reverse
Problem Description
You are given an integer array nums of length n.
Your task is to build a new array ans of length 2 * n by combining nums with its reverse:
- The first
nelements ofansare exactly the same asnums. - The next
nelements ofansare the elements ofnumsplaced in reverse order.
Formally, for every index i where 0 <= i <= n - 1:
ans[i] = nums[i]— the front half copiesnumsdirectly.ans[i + n] = nums[n - i - 1]— the back half mirrorsnums.
Return the resulting integer array ans.
For example, if nums = [1, 2, 3], then the front half is [1, 2, 3] and the reversed back half is [3, 2, 1], so ans = [1, 2, 3, 3, 2, 1].
How We Pick the Algorithm
Why Simulation / Basic DSA?
This problem maps to Simulation / Basic DSA through a short path in the full flowchart.
Following the described procedure step by step produces the answer.
Open in FlowchartIntuition
The problem directly tells us how each position in ans should be filled, so we can simply follow the formula step by step.
Notice that the array splits naturally into two halves:
- The front half (indices
0ton - 1) is just a straight copy ofnums, soans[i] = nums[i]. - The back half (indices
nto2 * n - 1) isnumsreversed. When we are at positioniin the original array, the matching back-half position isi + n, and the value placed there is the element counting from the end ofnums, which isnums[n - i - 1].
The key observation is that a single pass over nums lets us fill both halves at the same time. For each index i, we write nums[i] into the front and nums[n - i - 1] into the back. This avoids looping twice and keeps the logic clean.
So the approach is simply to allocate an array of size 2 * n, then loop once through nums and assign the two corresponding positions using the given formulas.
Solution Approach
Solution 1: Simulation
We create an array ans of length 2 * n, where n is the length of nums. The first n elements are the same as nums, and the next n elements are nums in reverse order.
The implementation follows these steps:
- Compute
n = len(nums)and initializeansas an array of2 * nzeros. - Loop through
numsonce using its indexiand valuex:- Set
ans[i] = xto fill the front half with the original elements. - Set
ans[i + n] = nums[n - i - 1]to fill the back half with the reversed elements.
- Set
- After the loop completes, return
ans.
Here only a simple one-pass loop and an output array are needed, so no extra data structures are required.
The time complexity is O(n), since we iterate through nums exactly once. Ignoring the space used by the answer array, the extra space complexity is O(1).
Example Walkthrough
Let's trace through the solution approach with a small example: nums = [4, 7, 9].
Setup:
n = len(nums) = 3- Initialize
ansas an array of2 * n = 6zeros:ans = [0, 0, 0, 0, 0, 0]
One-pass loop over nums:
We iterate with index i from 0 to n - 1, filling both halves on each step.
Iteration i = 0 (value x = 4):
- Front half:
ans[0] = nums[0] = 4 - Back half:
ans[0 + 3] = ans[3] = nums[3 - 0 - 1] = nums[2] = 9 - State:
ans = [4, 0, 0, 9, 0, 0]
Iteration i = 1 (value x = 7):
- Front half:
ans[1] = nums[1] = 7 - Back half:
ans[1 + 3] = ans[4] = nums[3 - 1 - 1] = nums[1] = 7 - State:
ans = [4, 7, 0, 9, 7, 0]
Iteration i = 2 (value x = 9):
- Front half:
ans[2] = nums[2] = 9 - Back half:
ans[2 + 3] = ans[5] = nums[3 - 2 - 1] = nums[0] = 4 - State:
ans = [4, 7, 9, 9, 7, 4]
Result:
- The loop completes and we return
ans = [4, 7, 9, 9, 7, 4].
Verification:
- Front half
[4, 7, 9]matchesnumsexactly. ✓ - Back half
[9, 7, 4]isnumsreversed. ✓
This confirms that a single pass fills both halves correctly: as i moves forward from the start of nums, the index n - i - 1 moves backward from the end, so the front gets the original order while the back gets the mirrored order.
Solution Implementation
1class Solution:
2 def concatWithReverse(self, nums: list[int]) -> list[int]:
3 # Number of elements in the input list
4 n = len(nums)
5
6 # Result list with double the size:
7 # first half holds the original order,
8 # second half holds the reversed order
9 ans: list[int] = [0] * (2 * n)
10
11 # Iterate over each element with its index
12 for i, x in enumerate(nums):
13 # Place the current element in the first half
14 ans[i] = x
15 # Place the mirrored element in the second half
16 ans[i + n] = nums[n - i - 1]
17
18 return ans
191class Solution {
2 /**
3 * Concatenates the input array with its reverse.
4 * The resulting array has the original elements in the first half
5 * and the reversed elements in the second half.
6 *
7 * @param nums the input integer array
8 * @return a new array of length 2 * nums.length containing
9 * the original array followed by its reverse
10 */
11 public int[] concatWithReverse(int[] nums) {
12 // Length of the original input array.
13 int length = nums.length;
14
15 // Result array is twice the size of the input.
16 int[] result = new int[2 * length];
17
18 for (int i = 0; i < length; i++) {
19 // Copy the original element into the first half.
20 result[i] = nums[i];
21
22 // Copy the corresponding element from the end into the second half,
23 // effectively building the reversed portion.
24 result[i + length] = nums[length - i - 1];
25 }
26
27 return result;
28 }
29}
301class Solution {
2public:
3 // Concatenate the input array with its reverse.
4 // The result has length 2 * n, where the first half is the
5 // original array and the second half is the array reversed.
6 vector<int> concatWithReverse(vector<int>& nums) {
7 int n = static_cast<int>(nums.size());
8
9 // Pre-allocate the result with exactly 2 * n slots.
10 vector<int> ans(2 * n);
11
12 for (int i = 0; i < n; ++i) {
13 // Copy the element at position i into the first half.
14 ans[i] = nums[i];
15
16 // Mirror the element into the second half:
17 // index (i + n) receives the element counted from the end.
18 ans[i + n] = nums[n - i - 1];
19 }
20
21 return ans;
22 }
23};
241/**
2 * Concatenates the input array with its reversed version.
3 * The result has length 2 * n, where the first half is the original
4 * array and the second half is the array in reverse order.
5 *
6 * @param nums - The input array of numbers.
7 * @returns A new array of length 2 * n containing nums followed by its reverse.
8 */
9function concatWithReverse(nums: number[]): number[] {
10 // Length of the original input array.
11 const n: number = nums.length;
12
13 // Allocate the result array with double the size.
14 const ans: number[] = new Array<number>(2 * n);
15
16 // Fill both halves of the result in a single pass.
17 for (let i = 0; i < n; ++i) {
18 // First half: copy elements in their original order.
19 ans[i] = nums[i];
20 // Second half: copy elements in reversed order.
21 ans[i + n] = nums[n - i - 1];
22 }
23
24 return ans;
25}
26Time and Space Complexity
-
Time complexity:
O(n), wherenis the length of the arraynums. The code iterates through the array exactly once using a singleforloop, performing constant-time operations (two assignments) in each iteration. Thus the total time grows linearly withn. -
Space complexity:
O(n), wherenis the length of the arraynums. The code allocates a new arrayansof size2 * nto store the result. Ignoring the output array, only a constant amount of extra space is used; counting the result array, the space requirement is proportional ton.
Pattern Learn more about how to find time and space complexity quickly.
Common Pitfalls
Pitfall 1: Confusing the mirror index formula
The most frequent mistake is getting the back-half index math wrong. When filling ans[i + n], you must place the element from the opposite end of nums, which is nums[n - i - 1]. Common erroneous variants include:
- Writing
nums[n - i]— this causes an off-by-one error and triggers anIndexErrorwheni = 0(accessingnums[n], which is out of bounds). - Writing
ans[i + n] = nums[i]— this copies the original order into the back half instead of reversing it, producing[1, 2, 3, 1, 2, 3]rather than[1, 2, 3, 3, 2, 1].
Solution: Always anchor the formula at the largest valid index. When i = 0, the mirror element should be the last element nums[n - 1]; when i = n - 1, it should be the first element nums[0]. The expression nums[n - i - 1] satisfies both boundary checks:
# i = 0 -> nums[n - 1] (last element) ✓ # i = n - 1 -> nums[0] (first element) ✓ ans[i + n] = nums[n - i - 1]
Pitfall 2: Mutating nums in place to build the reverse
Some attempt to reverse nums directly (e.g., nums.reverse() or nums.sort(reverse=True)) before concatenating. Calling nums.reverse() mutates the caller's input and corrupts the front-half values if done before they are copied. Sorting is plainly wrong since the task requires reversal, not ordering.
Solution: Never modify nums. Either use the index formula shown above, or build a fresh reversed copy without touching the original:
# Safe one-liner alternative that leaves nums untouched return nums + nums[::-1]
Here nums[::-1] creates a new reversed list via slicing, leaving nums intact.
Pitfall 3: Allocating the result with the wrong length
Initializing ans = [0] * n (instead of 2 * n) leads to an IndexError the moment you assign to ans[i + n]. Conversely, appending to an empty list while indexing into it (ans[i + n] on an empty ans) also fails.
Solution: Pre-size the array to exactly 2 * n before any index assignment, or use append-based / slicing construction consistently:
ans = [0] * (2 * n) # correct fixed-size allocation
Pitfall 4: Edge case of an empty input
When nums = [], n = 0 and the expected result is an empty list. The index-based loop handles this naturally (the loop body never executes), but ad-hoc solutions that assume at least one element—such as separately handling nums[0]—can crash.
Solution: Rely on the loop/slicing logic, which already returns [] for empty input without special casing.
Ready to land your dream job?
Unlock your dream job with a 5-minute quiz for a personalized study roadmap!
Get My RoadmapWhich two pointer techniques do you use to check if a string is a palindrome?
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion If you prefer videos here's a video that explains recursion in a fun and easy way Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask him
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity describes how the time needed
Want a Structured Path to Master System Design Too? Don’t Miss This!