Skip to content

3925. Concatenate Array With Reverse

Description

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 <= 100
  • 1 <= nums[i] <= 100

Solutions

Solution 1: Simulation

We create an array \(\textit{ans}\) of length \(2 \times n\). The first \(n\) elements are the same as \(\textit{nums}\), and the next \(n\) elements are \(\textit{nums}\) in reverse order.

Specifically, for \(0 \leq i \leq n - 1\), we set \(\textit{ans}[i] = \textit{nums}[i]\) and \(\textit{ans}[i + n] = \textit{nums}[n - i - 1]\).

Finally, return the array \(\textit{ans}\).

The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\).

1
2
3
4
5
6
7
8
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int[] concatWithReverse(int[] nums) {
        int n = nums.length;
        int[] ans = new int[2 * n];
        for (int i = 0; i < n; ++i) {
            ans[i] = nums[i];
            ans[i + n] = nums[n - i - 1];
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    vector<int> concatWithReverse(vector<int>& nums) {
        int n = nums.size();
        vector<int> ans(2 * n);
        for (int i = 0; i < n; ++i) {
            ans[i] = nums[i];
            ans[i + n] = nums[n - i - 1];
        }
        return ans;
    }
};
1
2
3
4
5
6
7
8
9
func concatWithReverse(nums []int) []int {
    n := len(nums)
    ans := make([]int, 2*n)
    for i, x := range nums {
        ans[i] = x
        ans[i+n] = nums[n-i-1]
    }
    return ans
}
1
2
3
4
5
6
7
8
9
function concatWithReverse(nums: number[]): number[] {
    const n = nums.length;
    const ans: number[] = new Array(2 * n);
    for (let i = 0; i < n; ++i) {
        ans[i] = nums[i];
        ans[i + n] = nums[n - i - 1];
    }
    return ans;
}

Comments