Count sort algorithm

Paul Kang
2 min readJan 12, 2024

A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.

You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).

Return the number of indices where heights[i] != expected[i].

Example 1:

Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation:
heights: [1,1,4,2,1,3]
expected: [1,1,1,2,3,4]
Indices 2, 4, and 5 do not match.

Example 2:

Input: heights = [5,1,2,3,4]
Output: 5
Explanation:
heights: [5,1,2,3,4]
expected: [1,2,3,4,5]
All indices do not match.

Example 3:

Input: heights = [1,2,3,4,5]
Output: 0
Explanation:
heights: [1,2,3,4,5]
expected: [1,2,3,4,5]
All indices match.

Constraints:

  • 1 <= heights.length <= 100
  • 1 <= heights[i] <= 100

class Solution:
# def heightChecker(self, heights: List[int]) -> int:
# # when you allow that you can use the “sorted” function from python,

# sortedHeights = sorted(heights)
# diffCount = 0
# for val1, val2 in zip(sortedHeights, heights):
# if val1 != val2:
# diffCount += 1

# return diffCount

def heightChecker(self, heights: List[int]) -> int:
# but, lets say that you are not allowed to use the built in sorted function.
# then, you need to implement sorting algorithm, this time, I am going to practice
# “Count sort” algorithm, which in worst case time complexity, it becomes O(N+M)

# Count sort algorithm is as follows:

# 1. find the maximum value of a given array (O(N))
# 2. create an array with zeros of the length: len(maxval) + 1
# 3. traverse the original array, count each element at its respective index
# 4. make the array cumulative sum
# 5. reverse traverse the orignal array and its value becomes index of the new array. as traversed, value of the helper array at its index gets -1 every time

# step 1 O(N)
maxval = max(heights)
# step 2 O(N)
helperArray = [0] * (maxval + 1)
outputArray = [0] * len(heights)
# step 3 O(N)
for val in heights:
helperArray[val] += 1
# step 4 O(N)
for idx in range(1, len(helperArray)):
helperArray[idx] = helperArray[idx] + helperArray[idx — 1]
# step 5
for idx in range(len(heights) — 1, -1, -1):
originalValue = heights[idx]
newIdx = helperArray[originalValue] — 1
outputArray[newIdx] = originalValue
helperArray[originalValue] -= 1

# now the output Array is sorted
diffCount = 0
for val1, val2 in zip(outputArray, heights):
if val1 != val2:
diffCount += 1

return diffCount

--

--