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
47 views
Written by Prashant Basnet
Prashant Basnet, a software engineer at Unisala.com, focuses on software development and enjoys building platforms to share knowledge. Interested in system design, data structures, and is currently learning NLP
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.