18. Copy an Array Without Using Built-in Copy Methods
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:
- Create an empty result array.
- Visit every element of the source array.
- Add each value to the result array.
- 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.