leetcode 1929 solution in java

Concatenation of Array

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.

Return the array ans.

The problem is taken from :- leetcode Problem

Approach:-

121
Index position is = 0Index position is = 1Index position is = 2

The given Array is mentioned above.

Our final Array is:-

121121
Index position is = 0Index position is = 1Index position is = 2Index position is = 3 which is(n+index position) where n is the length of the given arrayIndex position is = 4 which is(n+index position) where n is the length of the given arrayIndex position is = 5 which is(n+index position) where n is the length of the given array

If we look closely, we can find a pattern. The value is repeating after (n+index position) in each loop of the array.

Code:-

class Solution {
  public int[] getConcatenation(int[] nums) {
    final int n = nums.length;

    int[] ans = new int[n * 2];

    for (int i = 0; i < n; ++i)
      ans[i] = ans[i + n] = nums[i];

    return ans;
  }
}

For more problem solution, please visit:-Algorithm and Datastructure