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. Specifically, ans should be a concatenation of nums followed by nums. Return the array ans.

Example:

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

Clarifying Questions

  1. Q: Can nums be an empty array?
    • A: No, nums will have at least one element.
  2. Q: Are there any constraints on the elements within nums?
    • A: The problem does not specify constraints on the values, so any integer values are assumed to be valid.

Strategy

To solve this problem, we need to accomplish two key steps:

  1. Initialize an answer array with size 2n.
  2. Fill the first half of the ans array with the elements of nums.
  3. Fill the second half of the ans array with the elements of nums again.

This can be done using a simple loop to copy elements from nums to the ans array at appropriate positions.

Code

#include <vector>
using namespace std;

vector<int> getConcatenation(vector<int>& nums) {
    int n = nums.size();
    vector<int> ans(2 * n);  // Create a result array of size 2*n
    
    // Fill the first half and the second half
    for (int i = 0; i < n; ++i) {
        ans[i] = nums[i];
        ans[i + n] = nums[i];
    }
    
    return ans;
}

// Example usage:
// int main() {
//     vector<int> nums = {1, 2, 1};
//     vector<int> result = getConcatenation(nums);
//    
//     for (int val : result) {
//         cout << val << " ";
//     }
//     return 0;
// }

Time Complexity

This ensures that the solution is efficient with respect to both time and space for the given problem constraints.

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