18. Copy an Array Without Using Built-in Copy Methods

Difficulty:EasyPattern:Traversal / Array ConstructionTime:O(n)Space:O(n)

Create a new array containing the same elements as the input array without using built-in array copy methods.

How It Works & Algorithmic Design

Use direct traversal:

  1. Create an empty result array.
  2. Visit every element of the source array.
  3. Add each value to the result array.
  4. Return the newly created array.

Why This Approach Works Best

The operation demonstrates basic array traversal and explicit construction. Since a new array containing all $n$ elements is created, the space complexity is $O(n)$.

Example Walkthrough
Input: [10, 20, 30]
The source array contains three values.
Copy Process: result=[] -> [10] -> [10,20] -> [10,20,30]
Each source element is manually added to the new array.
Output: [10, 20, 30]
The returned array contains the same values but is a separate array.

Answer: Manually copy an array

function copyArray(arr) {
  const result = [];
  for (const value of arr) {
    result.push(value);
  }
  return result;
}
💡 Create a new array and copy each element one by one.
Key Takeaways
  • Manual copying demonstrates basic traversal and array construction.
  • The original array remains unchanged.
  • Creating a new array requires O(n) additional space.