MadAlgos Blog
Solved question on array
Welcome to our array problem-solving session!
In this session, we will be tackling an array-related question from LeetCode, a popular platform for coding interviews and competitive programming.
Arrays are fundamental data structures that allow us to store and manipulate a collection of elements in a sequential manner. They provide efficient access to individual elements and play a crucial role in solving many coding problems.
Today, we will dive into a specific array problem, applying our problem-solving skills and leveraging the power of arrays to arrive at an optimal solution.
So, let’s begin solving the question.
Question :
Concatenation of Array -
https://leetcode.com/problems/concatenation-of-array/description/
To solve this problem, we need to create a new array, ans, that is a concatenation of the input array nums with itself. The resulting array ans will have a length of twice the length of nums, where ans[i] will be equal to nums[i] and ans[i + n] will also be equal to nums[i], for 0 <= i < n. This essentially means that we need to append nums to itself.
To achieve this, we can follow a simple approach. We initialize an empty array ans and then iterate over the elements in nums. For each element num in nums, we append num to ans twice, once at its original index and once at its index plus n. Finally, we return the resulting array ans.
This approach ensures that ans is formed as the concatenation of two nums arrays, satisfying the given requirements.
Now, let's implement this approach and solve the problem.
class Solution{
public int[] getConcatenation(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[i];
}
return and;
}
}
In the above code, the getConcatenation function takes an integer array nums as input and returns the concatenated array ans as output. It creates a new array ans with a length of 2 * n, where n is the length of the input array nums.
Then, it iterates over the elements of nums using a for loop. For each element at index i, it assigns nums[i] to ans[i] and also assigns nums[i] to ans[i + n]. This ensures that the second half of ans contains the same elements as the first half.
Finally, it returns the resulting concatenated array ans.
Hope you enjoyed solving the problem!
Happy learning
Follow us on MADAlgos
Check out the following blogs for single-dimension arrays :
Introduction to arrays:
https://madalgos.in/blog-space/18
https://madalgos.in/blog-space/19
Basic operations on arrays:
https://madalgos.in/blog-space/20
https://madalgos.in/blog-space/21
Introduction to multidimensional arrays:
https://madalgos.in/blog-space/22
Basic operations on multidimensional arrays:
https://madalgos.in/blog-space/23
https://madalgos.in/blog-space/24
https://madalgos.in/blog-space/25