LeetCode #1929 – Concatenation of Array

Let’s solve LeetCode 1929 – Concatenation of Array problem. It’s from the Arrays section on LeetCode, and as usual, we’ll tackle it using C# today.

Before we jump into the code, let’s understand the problem statement.

This problem challenges you to create a new array by “duplicating” a given integer array. The resulting array should have twice the length of the original, with each element from the original array appearing twice consecutively (That’s the key to solve this challenge).

Understanding the Problem:
  • We are given an integer array nums of length n.
  • We need to create a new array ans of length 2n (twice the length of the original).
  • The elements in the new array ans should be arranged such that ans[i] == nums[i] and ans[i + n] == nums[i] for all indices i from 0 to n-1.

In simpler terms, the new array ans is the concatenation of two copies of the original array nums.

Alright, let’s start designing our solution:

1) We need to create a new array ans that can hold twice the number of elements as the original array nums.

public class Solution {
    public int[] GetConcatenation(int[] nums) {
        int[] ans = new int[nums.Length*2];
    }
}

2) We need to iterate through each element in the original array nums and copy it to the new array ans at two specific positions ( i and i + nums.Length).

public class Solution {
    public int[] GetConcatenation(int[] nums) {
        int[] ans = new int[nums.Length*2];
        
        for(int i = 0; i < nums.Length; i++){
            ans[i] = nums[i];
            ans[i + nums.Length] = nums[i];
        }
    }
}
  • The line ans[i] = nums[i] copies the element at index i from nums to the corresponding index i in the ans array. This ensures the first half of the ans array is a copy of the original nums.
  • The line ans[i + nums.Length] = nums[i] is the key part for concatenation. It copies the same element at index i from nums to an index that is nums.Length positions ahead of the current index i in the ans array. This effectively places a copy of each element from nums in the second half of the ans array.

3) Now we just need to return ans after the loop!

public class Solution {
    public int[] GetConcatenation(int[] nums) {
        int[] ans = new int[nums.Length*2];
        
        for(int i = 0; i < nums.Length; i++){
            ans[i] = nums[i];
            ans[i + nums.Length] = nums[i];
        }
        
        return ans;
    }
}

This solution iterates through the original array, copies each element to its corresponding position in the first half of the new array, and then copies it again to the calculated position in the second half, resulting in the desired concatenation.

This is the result for this solution: