You’re given a big array with Integral type value, How do you move all zero values within it to the front portion of the array in a Time Efficiency way?
e.g. 0,1,72,3,0,5,9,0,6,51,0,3 —> 0,0,0,0,1,72,3,5,9,6,51,3
Regards!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want to keep the order between the other items, loop backwards copying all non-zero items, then fill up with zero items at the beginning:
If the order of the items is not important, you can simply swap zero items with items at the beginning of the array:
Both algorithms are O(n).
(Examples in C#, but it should be close enough as it’s mostly a question about algorithms…)