Given an array of length n, build a new array of length 2 n. The first half is the original array, and the second half is the same array again.
DSA Animator › DSA Revision › Arrays › Concatenation of Array
Remember: a copy shifted by n lands at index i plus n. One loop can fill two positions at once. The video solves Concatenation of Array (LeetCode 1929, Easy) with the Basics pattern from the Arrays topic, and you can replay every step in the interactive Concatenation of Array animation.
Given an array of length n, build a new array of length 2 n. The first half is the original array, and the second half is the same array again.
For 1, 2, 1, the answer is 1, 2, 1, 1, 2, 1. The array simply appears twice, back to back.
You could append the array to a list twice, but that hides what the indexes are doing. The cleaner way is to understand where each value lands.
Every value at index i is copied to two places. Once at index i, and once at index i plus n.
Here n is 3, so the answer has 6 slots. Index 0 holds 1, so 1 goes to slot 0 and slot 3. Index 1 holds 2, so 2 goes to slot 1 and slot 4. Index 2 holds 1, so 1 goes to slot 2 and slot 5. The answer is 1, 2, 1, 1, 2, 1.
In code, create an array of size 2 n. Loop once over the input. Write each value at i, and again at i plus n. It's O of n time, and O of n space for the answer.
Remember: a copy shifted by n lands at index i plus n. One loop can fill two positions at once.