JustPaste.it

Concatenation of Array (LeetCode 1929): Two Ways, and What the Interviewer Is Really Checking

The problem: given an integer array nums of length n, return an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n. In other words, nums followed by nums again.

Example: [1, 2, 1] becomes [1, 2, 1, 1, 2, 1].

Version 1: the language does it

def getConcatenation(nums):
    return nums + nums

This is correct and idiomatic. In an interview it is fine to write it first, as long as you can say what it costs: a new list of size 2n is allocated and every element is copied once, so O(n) time and O(n) space.

Version 2: explicit indexing

Some interviewers want to see that you understand the index mapping, so be ready to write it by hand:

def getConcatenation(nums):
    n = len(nums)
    ans = [0] * (2 * n)
    for i in range(n):
        ans[i] = nums[i]
        ans[i + n] = nums[i]
    return ans

Same complexity, but now the i and i + n mapping is visible, which is the real point of the exercise.

Follow-ups worth preparing

  • Repeat k times. Generalise to ans[i + j * n] = nums[i] for j in 0..k-1, or use the modulo view: ans[t] = nums[t % n].
  • Do not allocate a copy. If the caller only needs to read the result, you can expose a view that maps index t to nums[t % n]. This is the same idea behind circular buffers and the "circular array" trick in Next Greater Element II, where you loop over 2n indices with i % n instead of building the doubled array.
  • In-place in a fixed buffer. If nums already has capacity 2n, copy from the front into the back half; no overlap problem because the halves are disjoint.

Takeaway

Easy problems are usually a warm-up for communication: state the one-liner, state its cost, show you know the index math, and connect it to the circular-array pattern before the interviewer asks.


I work on Linkjob AI, an interview assistant that helps you practise talking through problems like this one in real time. (Disclosure: affiliated.)