Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Introduction to Cyclic Sort Pattern
You are given an array of N numbers. The array contains every value from 1 to N, but the values are in the wrong order.
[3, 1, 5, 4, 2] becomes [1, 2, 3, 4, 5]
A normal sorting algorithm can solve this in O(N log N) time. A second counting array can solve it in O(N) time, but it needs O(N) extra space.
This problem gives us a useful fact. Every value has one correct position:
1belongs at index0.2belongs at index1.- A value
vbelongs at indexv - 1.
We do not need to compare values to discover their order
.....
.....
.....
Like the course? Get enrolled and start learning!
Reading Progress
0%