C++ Program for Concatenation of Array.

Given an integer array nums of length n, create a new array ans of length 2n such that ans is the concatenation of two nums arrays. 

  • ans[i] = nums[i] and ans[i+n] = nums[i]
  • 0 <= i < n

Example:
Input: nums = [3, 2, 4]
Output: ans = [3, 2, 4, 3, 2, 4]

Input: nums = [1, 3, 2, 4]
Output: ans = [1, 3, 2, 4, 1, 3, 2, 4]
Explaination: 
ans = [nums[0], nums[1], nums[2], nums[3], nums[0], nums[1], nums[2], nums[3]]

Algorithm 1:
  • Declare two integer arrays nums and ans of size n and 2n respectively.
  • Read the values of the array nums from the user.
  • Use a loop to copy the elements of nums into the first half of ans, i.e., from ans[0] to ans[n-1].
  • Use another loop to copy the elements of nums into the second half of ans, i.e., from ans[n] to ans[2n-1].
  • Print the elements of ans to the console.
C++ Code Implementation:
//C++ Program to concatenation of array
#include<iostream>
using namespace std;

//Concatenation function
void getConcatenation(int n, int nums[], int ans[]){
     // copying elements of nums into the first half of ans
   for(int i = 0; i < n; i++) {
      ans[i] = nums[i];
   }

   // copying elements of nums into the second half of ans
   for(int i = 0; i < n; i++) {
      ans[i+n] = nums[i];
   }
}
int main(){

    int nums[] = {1, 3, 2, 8};
    //size of given array
    int size = sizeof(nums)/sizeof(nums[0]);
    int ans[size*2];

    getConcatenation(size, nums, ans);

    for(int i = 0; i < 2*size; i++){
        cout<<ans[i]<<" ";
    }
}
Output:
1 3 2 8 1 3 2 8
  • Time Complexity: O(n) where is the size of the given array.
  • Space Complexity: O(2n) where 2n is the size of the answer array.

Algorithm 2:

In this algorithm, we are iterating over the output array ans and assigning nums[i % n] to ans[i], where % is the modulo operator. This ensures that we repeat the elements of nums from the beginning once we reach the end of the array. 

C++ Code Implementation:
//C++ Program to concatenation of array
#include<iostream>
#include<vector>
using namespace std;

//Concatenation function
vector<int> concatenateArrays(int n, int nums[]) {
   
    vector<int> ans(2 * n);
    for (int i = 0; i < 2 * n; i++) {
        ans[i] = nums[i % n];
    }
    return ans;
}
 
int main(){

    int nums[] = {1, 3, 2, 8};
    //size of given array
    int size = sizeof(nums)/sizeof(nums[0]);

    vector<int> ans  = concatenateArrays(size, nums);

    for(int i = 0; i < 2*size; i++){
        cout<<ans[i]<<" ";
    }
}
Output:
1 3 2 8 1 3 2 8
  • Time Complexity: O(n) where is the size of the given array.
  • Space Complexity: O(2n) where 2n is the size of the answer array.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS