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.
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.
- arrays hold a small number of elements, typically well under a thousand
- values may be negative, zero, or positive
- output length is always exactly twice the input length
- the original array's order is preserved in both halves
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].
nums = [3, 1, 4]. Output is 2n = 6 slots — element i lands at slot i AND slot i+n.
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 ansclass Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
ans = []
for _ in range(2): # same course, twice
for v in nums:
ans.append(v)
return ansclass Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] ans = new int[2 * n];
for (int i = 0; i < n; i++) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}
}class Solution {
public int[] getConcatenation(int[] nums) {
int[] ans = new int[2 * nums.length];
int k = 0;
for (int lap = 0; lap < 2; lap++) {
for (int v : nums) {
ans[k++] = v;
}
}
return ans;
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED