3 line python solution

  • 0

    class Solution(object):
    def moveZeroes(self, nums):
    for i in range(len(nums))[::-1]:
    if nums[i] == 0:
    If we iterate from the front and pop, the rest of the array will shift place and you will skip an element.
    If pop from the back then that is avoided by using [::-1] of range.
    popping from the middle of the list is more expensive because it has to shift all the elements behind, but from the test cases this is pretty fast (probably because the tests are really short). This is not as efficient as the two pointer solution (https://github.com/kamyu104/LeetCode/blob/master/Python/move-zeroes.py), but very very easy to understand.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.