LeetCode-in-Java

3925. Concatenate Array With Reverse

Easy

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:

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:

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:

Solution

public class Solution {
    public int[] concatWithReverse(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n * 2];
        int count = 0;
        for (int i = 0; i < n; i++) {
            ans[i] = nums[i];
            count++;
        }
        for (int i = n - 1; i >= 0; i--) {
            ans[count++] = nums[i];
        }
        return ans;
    }
}