o4-mini-2025-04-16· OpenAI
LMArena Human Preference 140K
You’re given an array. Move all zeroes to the end without changing the relative order of…
- User
You’re given an array. Move all zeroes to the end without changing the relative order of non-zero elements.
- Assistant
Here’s a neat in-place, one-pass solution in Python that slides all non-zero elements forward and fills the tail with zeroes:
def move_zeroes(nums): """ Moves all zeroes in the list nums to the end while preserving the order of non-zero elements. Args: nums (List[int]): The list to modify in-place. Returns: None: The list is modified directly. """ # 'last_non_zero' points to the index where the next non-zero # element should be placed. last_non_zero = 0 # First pass: whenever we see a non-zero, swap it into 'last_non_zero' for i in range(len(nums)): if nums[i] != 0: nums[last_non_zero], nums[i] = nums[i], nums[last_non_zero] last_non_zero += 1 # After this, all non-zeroes are in front [0..last_non_zero-1] # and the rest [last_non_zero..end] are zeroes (by construction). # Example arr = [0, 1, 0, 3, 12] move_zeroes(arr) print(arr) # Output: [1, 3, 12, 0, 0]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.