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
407 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:
[0, 1, 2, 3, 4] 0. 1. 2. 3. 4create a destination how our target looks like. From current to our ideal
{ 0: 0 1: 1 2: 2 3: 3 4: 4 }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
{ 0: 0, // 0 belongs at index 0 1: 1, // 1 belongs at index 1 2: 2, // 2 belongs at index 2 3: 3, // 3 belongs at index 3 4: 4 // 4 belongs at index 4 }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.
let n = nums.length let start = Array.from({ length: n }, (_, i) => i); let end = Array.from({ length: n }, (_, i) => i + 1); end[n - 1] = 0;function calculationOps(target) { let positionMap = {} for (let i = 0; i < n; i++) { positionMap[target[i]] = i } let ops = 0, visited = new Array(n).fill(false)for (let i = 0; i < n; i++) { if (!visited[i] && nums[i] !== target[i]) { let cycleSize = 0, hasZero = false, j = i while (!visited[j]) { visited[j] = true if (nums[j] === 0) { hasZero = true } cycleSize++ j = positionMap[nums[j]] } ops += hasZero ? cycleSize - 1 : cycleSize + 1 } } return ops }