Bird
Raised Fist0
DSA Goprogramming

Radix Sort Algorithm in DSA Go

Choose your learning style10 modes available
Mental Model
Radix sort sorts numbers by processing digits from least to most significant, grouping numbers by each digit step by step.
Analogy: Imagine sorting mail by zip code: first by the last digit, then the second last, and so on, until fully sorted.
Unsorted array:
[170, 45, 75, 90, 802, 24, 2, 66]

Buckets for digit 0-9:
0: []
1: []
2: []
3: []
4: []
5: []
6: []
7: []
8: []
9: []
Dry Run Walkthrough
Input: array: [170, 45, 75, 90, 802, 24, 2, 66]
Goal: Sort the array in ascending order using radix sort
Step 1: Sort numbers by least significant digit (units place)
Buckets:
0: [170, 90]
1: []
2: [802, 2]
3: []
4: [24]
5: [45, 75]
6: [66]
7: []
8: []
9: []
Reassembled array: [170, 90, 802, 2, 24, 45, 75, 66]
Why: Grouping by units digit arranges numbers partially by their last digit
Step 2: Sort numbers by second least significant digit (tens place)
Buckets:
0: [802, 2]
1: []
2: [24]
3: []
4: [45]
5: []
6: [66]
7: [170, 75]
8: []
9: [90]
Reassembled array: [802, 2, 24, 45, 66, 170, 75, 90]
Why: Grouping by tens digit refines order based on second digit
Step 3: Sort numbers by third least significant digit (hundreds place)
Buckets:
0: [2, 24, 45, 66, 75, 90]
1: [170]
2: []
3: []
4: []
5: []
6: []
7: []
8: [802]
9: []
Reassembled array: [2, 24, 45, 66, 75, 90, 170, 802]
Why: Grouping by hundreds digit completes sorting by most significant digit
Result:
Sorted array: [2, 24, 45, 66, 75, 90, 170, 802]
Annotated Code
DSA Go
package main

import (
	"fmt"
)

func getMax(arr []int) int {
	max := arr[0]
	for _, v := range arr {
		if v > max {
			max = v
		}
	}
	return max
}

func countingSort(arr []int, exp int) {
	output := make([]int, len(arr))
	count := make([]int, 10)

	// Count occurrences of digits
	for _, num := range arr {
		digit := (num / exp) % 10
		count[digit]++
	}

	// Change count[i] so it contains actual position
	for i := 1; i < 10; i++ {
		count[i] += count[i-1]
	}

	// Build output array from right to left to maintain stability
	for i := len(arr) - 1; i >= 0; i-- {
		digit := (arr[i] / exp) % 10
		count[digit]--
		output[count[digit]] = arr[i]
	}

	// Copy output to arr
	for i := 0; i < len(arr); i++ {
		arr[i] = output[i]
	}
}

func radixSort(arr []int) {
	if len(arr) == 0 {
		return
	}
	max := getMax(arr)

	// Sort by each digit
	for exp := 1; max/exp > 0; exp *= 10 {
		countingSort(arr, exp)
	}
}

func main() {
	arr := []int{170, 45, 75, 90, 802, 24, 2, 66}
	radixSort(arr)
	for i, v := range arr {
		if i > 0 {
			fmt.Print(", ")
		}
		fmt.Print(v)
	}
	fmt.Println()
}
for _, num := range arr { digit := (num / exp) % 10 count[digit]++ }
count occurrences of current digit for all numbers
for i := 1; i < 10; i++ { count[i] += count[i-1] }
transform count to positions for stable sorting
for i := len(arr) - 1; i >= 0; i-- { digit := (arr[i] / exp) % 10 count[digit]-- output[count[digit]] = arr[i] }
build output array from right to left to keep order stable
for i := 0; i < len(arr); i++ { arr[i] = output[i] }
copy sorted output back to original array
for exp := 1; max/exp > 0; exp *= 10 { countingSort(arr, exp) }
iterate over each digit place from least to most significant
OutputSuccess
2, 24, 45, 66, 75, 90, 170, 802
Complexity Analysis
Time: O(d * (n + k)) where d is number of digits, n is number of elements, k is digit range (10); because we sort by each digit using counting sort
Space: O(n + k) for output and count arrays used in counting sort
vs Alternative: Compared to comparison sorts like quicksort O(n log n), radix sort can be faster for fixed digit size numbers because it sorts in linear time relative to input size
Edge Cases
empty array
function returns immediately without error
DSA Go
if len(arr) == 0 { return } // handle empty array before proceeding
array with one element
array remains unchanged as it is already sorted
DSA Go
for exp := 1; max/exp > 0; exp *= 10 { countingSort(arr, exp) } // loop runs but sorting one element is trivial
array with duplicate numbers
duplicates remain in correct sorted order due to stable counting sort
DSA Go
for i := len(arr) - 1; i >= 0; i-- { ... } // stable output preserves duplicates order
When to Use This Pattern
When you need to sort integers or fixed-length strings efficiently without comparisons, reach for radix sort because it sorts by digit positions in linear time.
Common Mistakes
Mistake: Not using stable sorting for each digit causes incorrect final order
Fix: Use counting sort from right to left to maintain stability for each digit pass
Mistake: Forgetting to process all digit places up to the max number's highest digit
Fix: Loop over digits until max/exp is zero to cover all digit places
Summary
Radix sort sorts numbers by processing digits from least to most significant using stable counting sort.
Use it when sorting integers or fixed-length data where comparison-based sorting is slower.
The key insight is sorting by each digit step-by-step preserves order and achieves full sorting efficiently.

Practice

(1/5)
1. What is the main idea behind the Radix Sort Algorithm?
easy
A. Sort numbers by dividing the list into halves recursively
B. Sort numbers by processing individual digits from least to most significant
C. Sort numbers by comparing each pair directly
D. Sort numbers by swapping adjacent elements repeatedly

Solution

  1. Step 1: Understand Radix Sort approach

    Radix Sort sorts numbers by grouping digits and sorting them digit by digit, starting from the least significant digit.
  2. Step 2: Compare with other sorting methods

    Unlike comparison-based sorts (like bubble or merge sort), Radix Sort processes digits individually without direct element comparisons.
  3. Final Answer:

    Sort numbers by processing individual digits from least to most significant -> Option B
  4. Quick Check:

    Radix Sort = Digit-wise sorting [OK]
Hint: Radix Sort sorts digits from right to left [OK]
Common Mistakes:
  • Thinking Radix Sort compares elements directly
  • Confusing Radix Sort with divide and conquer methods
  • Assuming it swaps adjacent elements like bubble sort
2. Which of the following is the correct way to initialize a slice of buckets for Radix Sort in Go?
easy
A. buckets := [][]int{}
B. buckets := make([]int, 10)
C. buckets := make([][]int, 10)
D. buckets := [10]int{}

Solution

  1. Step 1: Identify bucket type needed

    Radix Sort uses buckets to hold multiple integers per digit, so each bucket must be a slice of ints.
  2. Step 2: Choose correct slice initialization

    Using make([][]int, 10) creates a slice of 10 slices, perfect for buckets 0-9.
  3. Final Answer:

    buckets := make([][]int, 10) -> Option C
  4. Quick Check:

    Slice of slices for buckets = buckets := make([][]int, 10) [OK]
Hint: Buckets hold slices, so use [][]int with make [OK]
Common Mistakes:
  • Using single int slice instead of slice of slices
  • Using array instead of slice for dynamic buckets
  • Initializing empty slice without length
3. What will be the output of the following Go code snippet using Radix Sort on the array [170, 45, 75, 90, 802, 24, 2, 66]?
package main
import "fmt"
func main() {
  arr := []int{170, 45, 75, 90, 802, 24, 2, 66}
  radixSort(arr)
  fmt.Println(arr)
}

func radixSort(arr []int) {
  max := getMax(arr)
  exp := 1
  for max/exp > 0 {
    countSort(arr, exp)
    exp *= 10
  }
}

func getMax(arr []int) int {
  max := arr[0]
  for _, v := range arr {
    if v > max {
      max = v
    }
  }
  return max
}

func countSort(arr []int, exp int) {
  n := len(arr)
  output := make([]int, n)
  count := make([]int, 10)

  for i := 0; i < n; i++ {
    index := (arr[i] / exp) % 10
    count[index]++
  }

  for i := 1; i < 10; i++ {
    count[i] += count[i-1]
  }

  for i := n - 1; i >= 0; i-- {
    index := (arr[i] / exp) % 10
    output[count[index]-1] = arr[i]
    count[index]--
  }

  for i := 0; i < n; i++ {
    arr[i] = output[i]
  }
}
medium
A. [2 24 45 66 75 90 802 170]
B. [802 170 90 75 66 45 24 2]
C. [170 45 75 90 802 24 2 66]
D. [2 24 45 66 75 90 170 802]

Solution

  1. Step 1: Understand Radix Sort process on given array

    Radix Sort sorts by digits from least significant to most significant. After sorting by units, tens, and hundreds place, the array becomes sorted.
  2. Step 2: Trace final sorted array

    The final sorted array is ascending: [2, 24, 45, 66, 75, 90, 170, 802].
  3. Final Answer:

    [2 24 45 66 75 90 170 802] -> Option D
  4. Quick Check:

    Radix Sort output = Sorted ascending array [OK]
Hint: Radix Sort outputs sorted array ascending [OK]
Common Mistakes:
  • Confusing order of digits processed
  • Misreading output as original array
  • Mixing up output with descending order
4. Identify the bug in this Radix Sort countSort function snippet in Go:
func countSort(arr []int, exp int) {
  n := len(arr)
  output := make([]int, n)
  count := make([]int, 10)

  for i := 0; i < n; i++ {
    index := (arr[i] / exp) % 10
    count[index]++
  }

  for i := 1; i < 10; i++ {
    count[i] += count[i-1]
  }

  for i := 0; i < n; i++ {
    index := (arr[i] / exp) % 10
    output[count[index]-1] = arr[i]
    count[index]--
  }

  for i := 0; i < n; i++ {
    arr[i] = output[i]
  }
}
medium
A. The last for loop should iterate backwards from n-1 to 0
B. The count array size should be 100 instead of 10
C. The output slice should be initialized with zeros explicitly
D. The index calculation should use modulo 100 instead of 10

Solution

  1. Step 1: Check order of placing elements in output

    To maintain stable sorting, elements must be placed from right to left (backwards) in output.
  2. Step 2: Identify incorrect loop direction

    The code uses a forward loop (0 to n-1) which breaks stability; it should loop from n-1 down to 0.
  3. Final Answer:

    The last for loop should iterate backwards from n-1 to 0 -> Option A
  4. Quick Check:

    Stable sort needs backward loop [OK]
Hint: Place elements backward to keep stable order [OK]
Common Mistakes:
  • Looping forward breaks stability
  • Changing count array size unnecessarily
  • Misunderstanding index calculation
5. You want to sort a list of strings representing numbers with varying lengths using Radix Sort in Go. Which approach correctly adapts Radix Sort for this case?
hard
A. Pad all strings with leading zeros to equal length, then sort digit by digit from right to left
B. Sort strings by length first, then apply Radix Sort on digits from left to right
C. Convert strings to integers and apply normal Radix Sort directly
D. Use Radix Sort only on the first character of each string

Solution

  1. Step 1: Handle varying string lengths

    Pad strings with leading zeros so all have equal length, ensuring digit positions align.
  2. Step 2: Apply Radix Sort digit by digit from right to left

    After padding, sort from least significant digit (rightmost) to most significant (leftmost) to maintain correct order.
  3. Final Answer:

    Pad all strings with leading zeros to equal length, then sort digit by digit from right to left -> Option A
  4. Quick Check:

    Padding equalizes length for Radix Sort [OK]
Hint: Pad strings to same length before sorting digits [OK]
Common Mistakes:
  • Sorting by length first breaks digit alignment
  • Converting strings to int may overflow or lose leading zeros
  • Sorting only first character ignores full number
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