Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Think Like an Engineer: Optimize Swaps with Cycle Insight | Sort Array | Moving Items to Empty Space
May 17, 2025
341 views
Written by Prashant Basnet
👋 Welcome to my Signature, a space between logic and curiosity.
I’m a Software Development Engineer who loves turning ideas into systems that work beautifully.
This space captures the process: the bugs, breakthroughs, and “aha” moments that keep me building.
You are given an integer array nums of size n containing each element from 0 to n - 1 (inclusive). Each of the elements from 1 to n - 1 represents an item, and the element 0 represents an empty space.
For example, if n = 4, nums is sorted if:
Example 1:
Example 2:
Example 3:
create a destination how our target looks like. From current to our ideal
now we need to compare the current one
The order of the elements in the array matter more than the location of 0.We need all numbers in order (1,2,3,...) with 0 at either end.
Example Insight:
The numbers themselves need to be in order (1,2,3,4) regardless of where 0 is
We can fix the sequence first, then handle 0 last
Step 1: Create Mapping
Step 2: Find Cycles
Start at index 0 (value = 4):
Step 3: Calculate Operations for Cycle
Remaining Element:
Visualising the Operations
Original: [4,2,0,3,1]
But our cycle approach counted this as 3 operations because it's smarter about swaps.