Is there a more efficient algorithm to flatten an array?

I am aware of the recursive way to flatten a nested array. There are several solutions on stackoverflow (both in java and javascript - some using built in libraries).

But the time complexity of these solutions is O(n^2)! I was wondering if there is an algorithm which could do better.

Thanks in advance for your help!

Upvotes: 1

Views: 2392

Answers (1)

fdreger
fdreger

Reputation: 12495

You are either mistaken or you define your n as the root square of number of elements to process.

All the sane solutions of the array flattening problem are O(n), where n depends on the total number of elements (because, essentially, you need to scan them all, each of them only once). Flattening an array is not an algorithmic problem, it's just the question of getting it in an "elegant" snippet.

Upvotes: 4

Related Questions