NeetCode #1LC-1929EasyArrays & HashingNC 250
← Back to All Problems

#1 · #1929 · Concatenation of Array(数组串联)

📌 Problem Statement & Constraints

Given an integer array nums of length n, build an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n. In other words, return nums concatenated with itself. Constraints: 1 <= nums.length <= 1000, 1 <= nums[i] <= 1000.

💡 Core Algorithmic Approaches

  1. The definition is literally nums + nums, so the simplest correct answer is the list concatenation operator.
  2. For an explicit solution, allocate a result of length 2n and fill it with a single loop using the modulo trick res[i] = nums[i % n].
  3. Or copy nums into both halves with two slice assignments, which is the most explicit version.
  4. This is a warm-up problem; the interviewer is checking that you can state the obvious answer without over-engineering.

💻 Benchmark Python3 Implementation

class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        return nums + nums


# Explicit two-pass version, useful if the follow-up asks for in-place style
class Solution2:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        n = len(nums)
        res = [0] * (2 * n)
        for i in range(n):
            res[i] = nums[i]
            res[i + n] = nums[i]
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): both variants touch each element once (the + operator copies the whole list once).
💾 Space Complexity
O(n) for the output, which is unavoidable since the result is twice the input length.

⚠️ Interview Pitfalls & Follow-ups

  • Using nums * 2 and worrying about aliasing: for a list of ints this is safe -- * creates new references to the same immutable ints, and there is no shared mutable sub-object.
  • Mutating the input with nums.extend(nums): this returns None and modifies the caller's list, which is a side effect the problem does not ask for.
  • Overthinking it: this is an Easy warm-up; the one-liner is the expected answer.