Rearrange the array in place so that every 5 is moved to the end, while the
relative order of all non-5 values is preserved. Return the rearranged slice.
fiveSort(nums)
Input format: space-separated integers.
[12, 5, 1, 5, 12, 7] // → [12, 1, 12, 7, 5, 5]
[5, 5, 5] // → [5, 5, 5]
[1, 2, 3] // → [1, 2, 3]
The goal: push every 5 to the back while keeping everything else's relative order. A first instinct might build a new array — copy non-fives, then append fives. That works, but uses memory proportional to the input when the problem can be solved in place.
Compact non-five values toward the front using two pointers starting at the beginning: a "read" pointer scanning every element, and a "write" pointer marking the next open slot for a kept value.
As read walks forward, whenever it finds a non-5, that value goes to the write pointer's position, and write advances by one. When read finds a 5, nothing is written — write just stays put. Since write only advances when a kept value is placed, in the same left-to-right order read encounters values, relative order is automatically preserved.
Write only advances when read has just placed a value, and read always moves at least as fast. So write's position is always ≤ read's — you never overwrite a value read hasn't looked at yet.
Once read has scanned the whole array, every non-five is compacted into positions 0 through write-1. Everything from write's final position onward is stale, so a final pass overwrites those slots with 5.
This does the entire rearrangement in one pass with no extra memory beyond two integer positions — modifying in place rather than allocating a second array. Any "filter and compact while preserving order" problem reduces to this same read/write scan.
def five_sort(nums):
write = 0
for read in range(len(nums)):
if nums[read] != 5:
nums[write] = nums[read]
write += 1
while write < len(nums):
nums[write] = 5
write += 1
return nums
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.