Python 3D Academyবাংলা

Cyclic sort: every number in its own seat

🌍 In real life. At a school prize-giving, seats 1 to 30 are numbered and so are the invitation cards. Each guest walks to the seat on their card; if someone is already sitting there, they swap, and the person moved walks to their seat. When everyone has sat down, an empty seat tells you whose card went missing, and two people holding the same number means a card was printed twice.

When a list holds the numbers 1 to n (or 0 to n − 1), every number has its own "seat", its index, and the same trick finds the missing and repeated ones without sorting and without extra memory.

The idea in one sentence: when the values are 1 to n, value x belongs at index x − 1, so keep swapping the number at i into its home until the right number (or a copy of it) is there; then one scan shows which numbers are missing or repeated, in O(n) time and O(1) extra memory.

Its words:

  • home: the index a value belongs at, x - 1 for values 1 to n
  • cyclic sort: placing each value at its home by swapping; the swaps follow cycles of misplaced numbers
  • in place: no second list, only swaps inside the one you have

Step by step, for [3, 1, 2]:

  1. i = 0 holds 3, whose home is index 2. Index 2 holds 2, not 3, so swap: [2, 1, 3]. Now 3 is home for good.
  2. Still at i = 0: it holds 2, home index 1, which holds 1. Swap: [1, 2, 3].
  3. i = 0 holds 1, its own home, so move on: i = 1, then i = 2, both already home.

The pointer i only moves on when the number at i is home, or when a copy of it is already sitting in its home:

Missing and repeated numbers. Run the cyclic sort, then read the list: wherever nums[i] != i + 1, the number i + 1 is missing, and the number sitting there, nums[i], is a repeat that had nowhere else to go. The check nums[i] != nums[home] is what makes repeats safe: when a copy is already home, swapping would only swap the two copies for ever.

Why it is correct, and what it costs. Every swap puts at least one number at its home, and a number at its home is never moved again, so there are at most n swaps. Between swaps, i only goes forward, at most n times. That is at most 2n steps: O(n) time, O(1) extra memory. Sorting first would cost O(n log n), and a set of the numbers seen would cost O(n) memory.

For 0 to n with one missing (LeetCode 268) there is an even shorter way: the numbers should add up to n(n + 1)/2, and whatever is missing is the difference, n * (n + 1) // 2 - sum(nums).

def cyclic_sort(nums):
    i = 0
    while i < len(nums):
        home = nums[i] - 1
        if nums[i] != nums[home]:
            nums[i], nums[home] = nums[home], nums[i]
        else:
            i += 1


cards = [4, 3, 2, 7, 8, 2, 3, 1]
cyclic_sort(cards)
print(cards)
print("missing:", [i + 1 for i, x in enumerate(cards) if x != i + 1])
print("repeated:", [x for i, x in enumerate(cards) if x != i + 1])

nums = [3, 0, 1]
print("0..3 is missing", 3 * 4 // 2 - sum(nums))
Seats 5 and 6 stayed empty, and the 3 and 2 sitting in them are the extra copies.

Mistakes and edge cases.

  • Comparing with the index instead of the home's value. if nums[i] != i + 1: swap, with a repeat in the list, keeps swapping two equal numbers for ever. Compare nums[i] with nums[home].
  • Moving i after every swap. The number that arrives at i may also be in the wrong place; i must stay until the spot is settled.
  • Values outside 1 to n. A 0 or an n + 1 has no home: nums[home] raises IndexError: list index out of range or, for 0, quietly uses nums[-1]. Check the range first, or skip such values.
  • Changing a list the caller still needs. Cyclic sort reorders the list it is given; copy it first (nums[:]) if that matters.

Quiz

  1. What does this print?

    nums = [2, 3, 1, 5, 4]
    i = 0
    swaps = 0
    while i < len(nums):
        home = nums[i] - 1
        if nums[i] != nums[home]:
            nums[i], nums[home] = nums[home], nums[i]
            swaps += 1
        else:
            i += 1
    print(nums, swaps)
  2. Why does cyclic sort take only O(n) time?

    • Each swap puts a number at its home for good, so there are at most n swaps
    • It compares every pair of numbers once
    • It halves the list each round
  3. After a cyclic sort of [3, 1, 3], index 1 holds 3 instead of 2. What does that tell you?

    • 2 is missing and 3 is repeated
    • 1 is missing
    • The list wasn't sorted
  4. For [1, 1] this loop never ends. Which line is wrong?

    def cyclic_sort(nums):
        i = 0
        while i < len(nums):
            home = nums[i] - 1
            if nums[i] != i + 1:
                nums[i], nums[home] = nums[home], nums[i]
            else:
                i += 1

Coding tasks

  1. Seats are numbered 1 to n, and cards (n numbers, each from 1 to n) may have repeats. Write missing_seats(cards): the numbers from 1 to n that are not in the list, in increasing order. Use a cyclic sort (O(1) extra memory besides the answer).

  2. nums holds n + 1 numbers, each from 1 to n, so at least one number repeats. Write find_repeat(nums) that returns a repeated number, using cyclic-sort swaps: the moment the number at i is not home but its home already holds the same number, you have found a repeat.