Crushing Tech Interviews with the Cyclic Sort Pattern

·

2 min read

This pattern is useful when dealing with problems involving arrays containing numbers in a range.

How would you solve the following problem?

Given n distinct numbers from 0 to n. Find the missing number.

Key words to pick out here: distinct, 0 to n (range)

Since we know that the numbers range from 0 to n, why don't we try and put them in their correct places? Once we put all the numbers that we have in their correct positions, we can easily determine the numbers that are missing.

Tip: Keep in mind that the range is 0 → n. The solution slightly differs if it's 1 → n. You should notice this in the interview.

Input: [4, 0, 3, 1]
Output: 2

The trick here is to sort the array in O(N) time whilst maintaining a constant time complexity O(1).

That's where cyclic sort comes in!

Heres the simple idea: We iterate the array one at a time, if the current number is not at the correct index, we swap it with the number at the correct index.

This should give you a better idea of what's going on:

image.png

Now, once we've sorted the values, we can then loop through the array and check where nums[i] != i

Pretty sweet!

def find_missing_number(nums: List[int]) -> int:
    i, n = 0, len(nums)

    while i < n:
        current_num = nums[i]
        if current_num < n and current_num != nums[current_num]:
            nums[i], nums[current_num] = nums[current_num], nums[i]
        else:
            i += 1

    for idx, num in enumerate(nums):
        if idx != num:
            return idx

    return n # if all the other elements are present, the missing number must be n

Tip: This version of the cyclic sort algorithm only works if there are distinct elements. If there aren't distinct elements you need be a bit clever and amend this algorithm a tiny bit. I'm going to let you figure this out!

Here's some other questions:

https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ (Easy)

https://leetcode.com/problems/find-all-duplicates-in-an-array/ (Medium)

If you enjoyed this article, please go support the people over at educative.io/courses/grokking-the-coding-in.. I've based this blog post on their content.