Move Zeros To End
An array 'arr' which have integers. You need to move all the zeros in the end of the array. You should preserve the relative order of other numbers in the array.
We should implement a solution that is more efficient than a naive brute force.
Example :
Given array arr = [12, 3, 0, 2, 8, 11, 0, 0, 6, 4, 0, 5, 7, 0, 8, 9, 0]
output: [12, 3, 2, 8, 11, 6, 4, 5, 7, 8, 9, 0, 0, 0, 0, 0, 0]
Discussion
This is my "code-golf-esque" solution.
I wasn't to sure about what the "naive brute force" is. My current solution should always run at
2n
wheren
is the number of integers in the array, this assumes thecombine
method just iterates the two arrays together.I'm 100% sure there is a
1n
approach, where you iterate over the array only 1 time, but I personally hate working on arrays I'm iterating over.edit I didn't see this was tagged as a Java problem, and the above is JavaScript, so it is what it is haha.
oh Sorry... I should make it language independent..
I think it can be done in single array iteration and having two pointer for swapping
Rust, my best shot at performance (checked with benchmarks):
did u try the given array in ur solution?
O(n) Clojure solution:
Swift solution:
Output:
I opted to just filter out all the zeros entirely/filter everything but zeros, then recombine in the correct order.