Bird
Raised Fist0
Interview Prepcyclic-sorteasyAmazonGoogle

Cyclic Sort (Place 1..n in Correct Positions)

Choose your preparation mode4 modes available
</>
IDE
def cyclic_sort(arr: list) -> list:public int[] cyclicSort(int[] arr)vector<int> cyclicSort(vector<int> &arr)function cyclicSort(arr)
def cyclic_sort(arr):
    # Write your solution here
    pass
class Solution {
    public int[] cyclicSort(int[] arr) {
        // Write your solution here
        return arr;
    }
}
#include <vector>
using namespace std;

vector<int> cyclicSort(vector<int> &arr) {
    // Write your solution here
    return arr;
}
function cyclicSort(arr) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Array not fully sorted or partially sortedSwapping only once per element instead of looping until correct position✅ Use a while loop to swap arr[i] with arr[arr[i]-1] until arr[i] == i+1 or duplicates prevent swap
Wrong: Infinite loop or timeout on arrays with duplicatesSwapping duplicates endlessly without checking if arr[i] == arr[arr[i]-1]✅ Add condition to skip swap if arr[i] == arr[arr[i]-1]
Wrong: Index out of range error or crash on empty or single element arraysNo base case checks for empty or very small arrays✅ Return input immediately if array length is 0 or 1
Wrong: Unnecessary swaps on already sorted arrays causing incorrect outputSwapping elements even if arr[i] == i+1✅ Swap only if arr[i] != i+1
Wrong: Timeout on large inputsUsing sorting or nested loops instead of O(n) cyclic sort✅ Implement index-based cyclic sort with O(n) time complexity
✓
Test Cases
t1_01basic
Input{"arr":[3,1,5,4,2]}
Expected[1,2,3,4,5]

Each number is placed at its correct index: 1 at index 0, 2 at index 1, etc.

t1_02basic
Input{"arr":[2,3,1,5,4]}
Expected[1,2,3,4,5]

Numbers rearranged so that each i is at index i-1.

t2_01edge
Input{"arr":[]}
Expected[]

Empty array input returns empty array.

t2_02edge
Input{"arr":[1]}
Expected[1]

Single element array remains unchanged.

t2_03edge
Input{"arr":[1,2,3,4,5]}
Expected[1,2,3,4,5]

Already sorted array remains unchanged.

t2_04edge
Input{"arr":[1,1,1,1]}
Expected[1,1,1,1]

All elements identical; duplicates remain unchanged.

t3_01corner
Input{"arr":[2,2,2,2,2]}
Expected[2,2,2,2,2]

All duplicates remain; no infinite swaps occur.

t3_02corner
Input{"arr":[4,3,2,7,8,2,3,1]}
Expected[1,2,2,3,3,4,7,8]

Array with duplicates and missing numbers placed as correctly as possible.

t3_03corner
Input{"arr":[5,4,3,2,1]}
Expected[1,2,3,4,5]

Reverse sorted array correctly sorted by cyclic sort.

t4_01performance
Input{"arr":[100000,99999,99998,99997,99996,99995,99994,99993,99992,99991,99990,99989,99988,99987,99986,99985,99984,99983,99982,99981,99980,99979,99978,99977,99976,99975,99974,99973,99972,99971,99970,99969,99968,99967,99966,99965,99964,99963,99962,99961,99960,99959,99958,99957,99956,99955,99954,99953,99952,99951,99950,99949,99948,99947,99946,99945,99944,99943,99942,99941,99940,99939,99938,99937,99936,99935,99934,99933,99932,99931,99930,99929,99928,99927,99926,99925,99924,99923,99922,99921,99920,99919,99918,99917,99916,99915,99914,99913,99912,99911,99910,99909,99908,99907,99906,99905,99904,99903,99902,99901]}
⏱ Performance - must finish in 2000ms

n=100000, O(n) cyclic sort must complete within 2 seconds.

Practice

(1/5)
1. You are given an unsorted array of integers that may contain duplicates and negative numbers. Your task is to find the first k positive integers missing from the array. Which algorithmic approach guarantees an optimal time complexity while handling duplicates and negatives correctly?
easy
A. Sort the array and then scan sequentially to find missing positive numbers.
B. Use dynamic programming to build a table of present and missing numbers.
C. Use cyclic sort to place numbers in their correct indices, then identify missing positives and track extras with a boolean array.
D. Use a max-heap to extract the smallest missing positive numbers one by one.

Solution

  1. Step 1: Understand problem constraints

    The array may contain duplicates and negative numbers, so naive sorting or heap approaches may be inefficient or incorrect.
  2. Step 2: Identify optimal approach

    Cyclic sort places numbers in their correct indices in O(n) time, ignoring negatives and duplicates. Then, a boolean array tracks extra numbers beyond the array length to find missing positives efficiently.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Cyclic sort + boolean array handles duplicates and negatives optimally [OK]
Hint: Cyclic sort handles duplicates and negatives efficiently [OK]
Common Mistakes:
  • Assuming sorting is always optimal
  • Using heaps which add unnecessary overhead
  • Confusing DP with presence tracking
2. You are given an unsorted array of integers that may contain duplicates, negatives, and zeros. Your task is to find the smallest continuous range of positive integers that are missing from the array. Which algorithmic approach guarantees an optimal O(n) time and O(1) space solution for this problem?
easy
A. Using a hash set to store all positive numbers and then checking for the missing range
B. Sorting the array and then scanning linearly to find the missing range
C. Using a dynamic programming approach to track presence of numbers
D. Using cyclic sort to place each positive integer at its correct index and then scanning for the missing range

Solution

  1. Step 1: Understand problem constraints

    The problem requires finding the smallest missing positive range in O(n) time and O(1) space, which excludes sorting (O(n log n)) and hash sets (O(n) space).
  2. Step 2: Identify the algorithm that achieves in-place linear time

    Cyclic sort places each positive integer at its correct index in the array, enabling a single pass to find the missing range efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Cyclic sort is known for in-place linear time sorting of numbers in range 1 to n [OK]
Hint: Cyclic sort achieves O(n) time and O(1) space for this problem [OK]
Common Mistakes:
  • Assuming sorting is optimal
  • Confusing hash set space with time complexity
3. You are given an unsorted integer array and need to find the smallest positive integer missing from it in O(n) time and O(1) extra space. Which algorithmic approach best guarantees this optimal solution?
easy
A. Sorting the array and then scanning for the first missing positive
B. Applying a greedy approach to pick the smallest missing positive at each step
C. Using a hash set to track presence of numbers and then scanning from 1 upwards
D. Placing each number in its correct index position using cyclic sort and then scanning

Solution

  1. Step 1: Understand the problem constraints

    The problem requires O(n) time and O(1) space, which rules out sorting (O(n log n)) and hash sets (O(n) space).
  2. Step 2: Identify the approach that rearranges elements in-place

    Cyclic sort places each number in its correct index (number k at index k-1), enabling a linear scan to find the first missing positive efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Cyclic sort achieves O(n) time and O(1) space [OK]
Hint: Optimal solution uses in-place cyclic sort [OK]
Common Mistakes:
  • Choosing sorting which is O(n log n)
  • Using hash sets which use extra space
  • Greedy approaches that don't guarantee correctness
4. Identify the bug in the following cyclic sort implementation for finding the corrupt pair:
medium
A. Line 6: Missing increment of i after else condition
B. Line 3: Incorrect initialization of n
C. Line 7: Swap logic is incorrect
D. Line 10: Return statement does not handle all cases

Solution

  1. Step 1: Analyze the while loop behavior

    Without incrementing i in the else branch, the loop can get stuck when nums[i] == nums[correct_index], causing infinite loop.
  2. Step 2: Identify fix

    Adding i += 1 in the else branch ensures progress and termination.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Infinite loop caused by missing index increment [OK]
Hint: Always increment index if no swap to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting to increment index after no swap
  • Swapping incorrectly
  • Misplaced return statements
5. Consider this buggy code snippet for finding the duplicate and missing numbers. Which line contains the subtle bug that can cause an infinite loop or incorrect result?
medium
A. Line 5: missing check before swapping
B. Line 3: initialization of i
C. Line 8: incrementing i
D. Line 10: returning the result

Solution

  1. Step 1: Analyze the swapping condition

    Without checking if nums[i] == nums[correct], swapping duplicates causes infinite loops or incorrect swaps.
  2. Step 2: Confirm other lines are correct

    Initialization, increment, and return lines are standard and not buggy here.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Missing conditional check before swap causes infinite loop [OK]
Hint: Always check if swap is needed to avoid infinite loops [OK]
Common Mistakes:
  • Forgetting to check for duplicates before swapping
  • Misplacing increment of index i
  • Returning wrong values after loop
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard