algoadvance

Leetcode 1929. Concatenation of Array

Problem Statement

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, you need to return the array ans.

Example:

Clarifying Questions

  1. Can the input array nums have negative integers?
    • Yes, the array can have negative integers.
  2. Is there a constraint on the size of the input array nums?
    • Yes, the constraint typically follows as 1 <= nums.length <= 1000.
  3. Do we need to preserve the order of elements in the ans array?
    • Yes, the order in ans should mirror the order in nums.

Let’s proceed with the solution.

Strategy

The problem is quite straightforward. We need to concatenate the array nums with itself to create the ans array.

Steps:

  1. Determine the length of the original array nums.
  2. Initialize a new array ans with a length of 2n.
  3. Populate the first n elements of ans with elements from nums.
  4. Populate the next n elements of ans with elements from nums again.
  5. Return the ans array.

Code

Here’s the Java implementation of the described strategy:

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 ans;
    }
}

Time Complexity

The time complexity for this solution is (O(n)), where (n) is the length of the input array nums. This is because we are iterating through the array once to populate the ans array.

The space complexity is also (O(n)) for the new array ans because we are creating a new array that is double the size of the input array nums.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI