Concatenate Array With Reverse Problem
#3925
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3925.
You are given an integer array nums of length n.
Construct a new array ans of length 2 * n such that the first n elements are the same as nums, and the next n elements are the elements of nums in reverse order.
Formally, for 0 <= i <= n - 1:
ans[i] = nums[i]ans[i + n] = nums[n - i - 1]
Return an integer array ans.
Example 1:
Input: nums = [1,2,3]
Output: [1,2,3,3,2,1]
Explanation:
The first n elements of ans are the same as nums.
For the next n = 3 elements, each element is taken from nums in reverse order:
- ans[3] = nums[2] = 3
- ans[4] = nums[1] = 2
- ans[5] = nums[0] = 1
Thus, ans = [1, 2, 3, 3, 2, 1].
Example 2:
Input: nums = [1]
Output: [1,1]
Explanation:
The array remains the same when reversed. Thus, ans = [1, 1].
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Approach: Simulation
Build ans with 2n slots. For every index i, set ans[i] = nums[i] for the first half and ans[i + n] = nums[n - 1 - i] for the second half, then return ans.
Complexity: O(n) time and O(n) extra space for the result.
class Solution:
def concatWithReverse(self, nums: List[int]) -> List[int]:
n = len(nums)
ans = [0] * (2 * n)
for i, x in enumerate(nums):
ans[i] = x
ans[i + n] = nums[n - i - 1]
return ans