◀ THE GRIND — ARRAYS & HASHING

Concatenation of Array

The drill: Double an array back-to-back with itself — the output runs the whole input twice in a row. A warm-up in index arithmetic: the second copy of element i lives exactly n slots downstream.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An array of integers shows up, and the job is to hand back a new array double the length, where the original sequence plays out once and then immediately plays out again in the same order.

Nothing about the values themselves matters — duplicates, negatives, and zeros all pass straight through untouched. The only real work is deciding where each value lands in the doubled output.

The output is a brand-new array; the input is left as it was found. Every element from the source shows up in exactly two slots of the result, n apart from each other.

EX 01
nums = [3, 1, 4]
[3, 1, 4, 3, 1, 4]
BOTH COPIES IN ORDER
EX 02
nums = [7]
[7, 7]
SINGLE ELEMENT, MINIMUM SIZE
EX 03
nums = [1, 1]
[1, 1, 1, 1]
DUPLICATES STAY DUPLICATED
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Picture the finished output before writing any code: the same course laid end to end, twice. Where does element i of the input land — both times?

HINT 2 THE STRUCTURE

The output's size is known before any work starts, so nothing ever needs to grow. Slot i and slot i + n always hold the same value.

HINT 3 ONE STEP FROM THE ANSWER

Allocate the 2n array up front and fill ans[i] and ans[i + n] inside one loop — or equivalently, fill slot j with nums[j % n].

COACH'S BOARD — THE PATTERN, STEP BY STEP
TWO LAPS, ONE PASSPATTERN · INDEX ARITHMETICnums = [3, 1, 4]
3
1
4
STEP 1

nums = [3, 1, 4]. Output is 2n = 6 slots — element i lands at slot i AND slot i+n.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/concatenation-of-array.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [0] * (2 * n)
        for i, v in enumerate(nums):
            ans[i] = v              # first lap
            ans[i + n] = v          # second lap, same stride
        return ans
TIME O(N)SPACE O(1) EXTRAPYTHON · RACE PACE · 8 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED