Skip to content

Latest commit

 

History

History
72 lines (49 loc) · 2.37 KB

025.md

File metadata and controls

72 lines (49 loc) · 2.37 KB

Difficulty: 🟢 Easy

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.

Examples:

Example 1:

Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]

Example 2:

Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]

Constraints:

  • n == nums.length
  • 1 <= n <= 1000
  • 1 <= nums[i] <= 1000

Solutions

O(n) solution in Python3

class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            nums.append(nums[i])
        return nums

The given solution creates the array ans by iterating through each element of the nums array and appending it to the end of the same nums array. It then returns the resulting array ans.

The algorithm works as follows:

  1. Iterate through each element num in the nums array.
    • Append num to the end of the nums array.
  2. Return the modified nums array, which contains the concatenation of nums with itself.

The algorithm appends each element of the nums array to the end of the same array, effectively concatenating it with itself.

Analysis of Time and Space Complexity

The time complexity of this algorithm is O(n), where n is the length of the nums array. The algorithm iterates through each element of the nums array once and performs constant-time operations.

The space complexity of the algorithm is O(1) as it modifies the nums array in-place without using any additional space.

Summary

The given solution creates the array ans by concatenating the input array nums with itself. It has a time complexity of O(n) and a space complexity of O(1), making it an efficient solution for the problem at hand.

NB: If you want to get community points please suggest solutions in other languages as merge requests.