arrays

01929. Leetcode: Concatenation of Array – Problem and Solution

In this blog post, we’ll explore a coding problem from LeetCode that involves concatenating an array with itself. We’ll discuss the problem statement and provide a solution using a simple algorithm.

The problem is as follows:

Given an integer array nums of length n, the task is to create a new array ans of length 2n such that ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). In simpler terms, the array ans is formed by concatenating two instances of the original array nums.

To solve this problem, we can use a straightforward approach. We create a new array ans with a length of 2n and fill it by copying elements from the original array nums twice. Here’s the solution in C#:

Solution

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

        for (int i = 0; i < length; i++)        
            newArray[i] = newArray[i + length] = nums[i];                 

        return newArray;
    }
}

In this solution, we iterate through the original array nums and copy each element to the corresponding positions in the new array newArray. The result is a concatenated array that meets the given conditions.

Conclusion

This LeetCode problem provides a simple exercise in array manipulation and indexing. The solution presented here demonstrates a basic algorithmic approach to solving the problem. Understanding and practicing such problems are valuable for improving algorithmic thinking and problem-solving skills in programming.

Leave a Reply

Your email address will not be published. Required fields are marked *


Categories


Tag Cloud

.net addEventListener algorithms angular api Array arrays async asynchronous basic-concepts big o blazor c# code components containers control-structures csharp data structures data types dictionaries docker dom dotnet framework functions git guide javascript json leetcode loops methods MVC node.js npm object oriented programming oop operators promisses server-side sorted typescript variables web framework