Java 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. 

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

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

Steps:

  • Create a new array ans[] = new int[2*n] of size 2n where n is the size of the given array. 
  • Copy the elements given into the new array where ans[i] = nums[i] and ans[i+n] = nums[i]
  • Return ans.
public class Main
{
    public static int[] getConcatenation(int[] nums) {
        
        int ans[] = new int[2*nums.length];
        
        for(int i = 0; i<nums.length; i++){
            ans[i] = nums[i];
            ans[i+nums.length] = nums[i];
        }
        return ans;
    }
public static void main(String[] args) {
    int nums[] = {1, 2, 1, 3};
    
    int[] ans = getConcatenation(nums);
    
    for(int i = 0; i<ans.length; i++) {
        System.out.print(ans[i]+" ");
    }
}
}
Output:
1 2 1 3 1 2 1 3

⚡ 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