1929. Concatenation of Array

Today, we’ll be looking at the following problem:

1929. Concatenation of Array

Prompt

We are given an array nums that has a total length of n elements. We want to create an array called ans that has a total length of 2n elements. The problem states that ans[i] == nums[i] and ans[i + n] == nums[i] meaning that at whichever index, the value located at that index will be identical to the value located at that index + n.

If this still isn’t clear, let’s observe the 1st example they provide. You can see that [1, 2, 1] is given as the input and [1, 2, 1, 1, 2, 1] is the output. If we take the value 2 as an example from the original array, the value 2 is located at index 1. In this case, if we add 1 with the length of the original array n, then the output array or ans at index 1 + 3 will also have a value of 2.

Input: [1, 2, 1]
Index: 0, 1, 2

Output: [1, 2, 1, 1, 2, 1]
Index: 0, 1, 2, 3, 4, 5

Pseudocode

Unless it’s specifically stated in the prompt, you either have the choice of appending each element back into the array as you iterate through it in-place or you can instantiate a new array and populate that array with 2n elements. My code will reflect the former as I wanted to save space by performing the algorithm in-place.

Pseudocode

Code

Code (Python)

Thank you for reading!

In case if you haven’t yet joined my Discord server where I host daily sessions on data structures & algorithms for free, please join via the link shared below.

Discord

If you have any questions or comments, please don’t feel afraid to connect with me on any of the platforms below or feel free to send me an email at cloudiosx@gmail.com

LinkedIn

GitHub

Portfolio

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
John Kim

iOS Developer | Full Stack Developer | Software Engineer | LinkedIn: john-kim-developer | GitHub: cloudiosx | Portfolio: cloudiosx.com