DSA AnimatorREVISION VIDEOS
← Back to problems
New

Concatenation of Array — LeetCode 1929 video explanation

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.

Loading videos…

DSA Animator › DSA Revision › Arrays › Concatenation of Array

Key moments in the Concatenation of Array video

0:04Problem0:13Example0:20Brute force0:28Key idea0:35Dry run0:52Code1:03Takeaway

What you will learn

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.

Concatenation of Array video transcript

Problem

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.

Example

For 1, 2, 1, the answer is 1, 2, 1, 1, 2, 1. The array simply appears twice, back to back.

Brute force

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.

Key idea

Every value at index i is copied to two places. Once at index i, and once at index i plus n.

Dry run

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.

Code

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.

Takeaway

Remember: a copy shifted by n lands at index i plus n. One loop can fill two positions at once.

More Arrays revision videos

← All 185 DSA revision videos