Leetcode

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.

Danilo Cavalcante

Working with web development since 2005, currently as a senior programmer analyst. Development, maintenance, and integration of systems in C#, ASP.Net, ASP.Net MVC, .Net Core, Web API, WebService, Integrations (SOAP and REST), Object-Oriented Programming, DDD, SQL, Git, and JavaScript

Recent Posts

Understanding Inheritance in C#

Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…

15 hours ago

Classes and Objects in C#: Object-Oriented Programming

In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…

2 days ago

Collections and LINQ Queries in C#

In modern C# programming, working with data collections is a common task. Understanding how to…

4 days ago

Exception Handling in C#: try-catch, finally, and Custom Exceptions

Exception handling is a critical part of writing robust and maintainable C# applications. It allows…

5 days ago

Do Docker Containers Take Up Space?

One of the common questions among Docker users is whether Docker containers consume disk space.…

6 months ago

How to Use “Order By” in C#

Sorting data is a common operation in programming, allowing you to organize information in a…

6 months ago