Lesson overview · Free interview practice

Cyclic Sort

Sort an array with minimal extra space.

Topics in the full lesson
  • Concept and Use Cases
  • When to Use
  • Time and Space Complexity
  • Sorting an Array of Numbers from 1 to n
  • Finding Missing Numbers
  • Finding Duplicate Numbers

Practice Problems

Work through a question before revealing its explanation. These questions and answers are free; Premium adds the full lesson walkthrough, examples and implementation detail.

Completion marks record your own progress, not an automatically checked result. The task type does not determine whether it is optional.

Question

Given an array nums of n integers where each integer is in the range [1, n], return an array of all the integers in [1, n] that do not appear in nums. Solve in O(n) time without using O(n) extra space (mark indices in-place).

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Question

Given an integer array nums of length n where each element is in the range [1, n] and each appears at most twice, return an array of all integers that appear exactly twice. Solve in O(n) time using O(1) extra space.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Question

Given an unsorted integer array nums that may contain negatives, zeros, and duplicates, return the smallest positive integer that does not appear in it. Your algorithm must run in O(n) time and use O(1) auxiliary space.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Explore the full Cyclic Sort material

Premium includes the complete lessons and implementation references. Free practice questions remain available without a subscription.

All course tracks & premium content
From basics to advanced masterclasses
Built for JS/TS developers like you
Real-world tips & common pitfalls
Upgrade to Premium