Copy an Array

Solve this Problem
Easy5 min
Topics
Companies
Given an array nums, return a new array containing the same values in the same order. Copying exposes an important detail: in most languages an array variable holds a referenceReferenceA value that points to where an object lives in memory. Copying a reference gives a second name for the same object, not a new object. to the data. Writing copy = nums creates a second name for the same array, not a new one — a true copyCopy (Shallow Copy)A new array that holds the same values in its own memory, so changing one does not affect the other. needs its own memory filled with the values.

Test Case 1:

Input:nums = [5, 1, 8]
Output:[5, 1, 8]
Explanation:A new array with the same values in the same order.

Test Case 2:

Input:nums = [0]
Output:[0]
Explanation:One element copied.

Constraints

  • ◆1 ≤ nums.length ≤ 1000
  • ◆-1000000 ≤ nums[i] ≤ 1000000

Try the Dry Run

Approach & Solutions

Copy Element by ElementGood

Create a new array of the same length, then copy the value at each index from the original into the new array. The result lives in its own memory, so changing it later cannot affect the original.

TimeO(n)
SpaceO(n)
class Solution { public int[] copyArray(int[] nums) { int[] copy = new int[nums.length]; for (int i = 0; i < nums.length; i++) { copy[i] = nums[i]; } return copy; } }
Built-in CopyOptimal

Every language has a one-step way to duplicate an array: nums.clone() in Java, list(nums) in Python, copying a vector by value in C++, memcpy into newly allocated memory in C, and the spread syntax [...nums] in JavaScript.

TimeO(n)
SpaceO(n)
class Solution { public int[] copyArray(int[] nums) { int[] copy = nums.clone(); return copy; } }

Related Problems