Pankaj Tanwar
Published on

Concatenation of Array.

Authors

Problem of the day - Concatenation of Array

Tag - Easy

Problem says, Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).

Specifically, ans is the concatenation of two nums arrays.

Yay, pretty easy!

Create a new array of length 2*n and, iterate over the original array and push element to i and i+n index. And tada, it's done.

I directly coded the solution.

class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int size = nums.size();
vector<int> res(2*size, 0);
for(int i=0;i<nums.size();i++) {
res[i] = nums[i];
res[i+size] = nums[i];
}
return res;
}
};

Time and space both are o(n). And total run time on leetcode is 8ms, with 12.4 MB space.

Umm, can this solution be improved further? Can I avoid using an extra array? What if I push to the same array?

class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n = nums.size();
for(int i=0;i<n;i++) {
nums.push_back(nums[i]);
}
return nums;
}
};

Yay! I just removed extra array. Total run time is now 4ms on leetcode.

Well, I decided to try STL here. Just to make this code fancy.

class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
nums.insert(nums.end(), nums.begin(), nums.end());
return nums;
}
};

A pretty neat and clear solution. For those who are not aware of insert() function in C++, it is used for inserting values in a vector. First argument is the location and second is the values.

You can read more about it here

By the way, this method is slow. It took 12ms and 12.7MB memory.


You might like previous editions of my coding diary -