Five Sort

Five Sort

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.

Examples

[12, 5, 1, 5, 12, 7]   // → [12, 1, 12, 7, 5, 5]
[5, 5, 5]              // → [5, 5, 5]
[1, 2, 3]             // → [1, 2, 3]

Walkthrough

Thinking it through

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.

The read/write pointer idea

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.

Why the write pointer can never get ahead of the read pointer

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.

Filling in the fives

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.

Why this beats the naive approach

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.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.