KatInterview

Arrange Garment Sizes in Standard Order

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringscounting-sortstring-manipulationlinear-time

Last updated

Tests understanding of counting sort for a fixed alphabet, achieving linear time complexity instead of comparison-based sorting.

You receive a string garments containing only the characters 'S', 'M', and 'L', which represent garment sizes (Small, Medium, Large). Rearrange the string so that all Small sizes appear first, followed by all Medium sizes, and finally all Large sizes.

Write a function arrange_garment_sizes(garments: str) -> str that returns the rearranged string.

Constraints

  • The input string length is between 0 and 1,000,000 characters
  • The string contains only the characters 'S', 'M', and 'L'
  • Your solution should run in O(n) time where n is the string length
  • Use O(1) auxiliary space (the output string itself is not counted)

Examples

Example 1

Input: arrange_garment_sizes('LMSMS')

Output: 'SSMML'

Example 2

Input: arrange_garment_sizes('MMM')

Output: 'MMM'

Hints

Hint 1

With only three distinct values, do you really need a general-purpose sorting algorithm?

Hint 2

Count how many times each character appears, then reconstruct the result.

Hint 3

This is counting sort with a three-element alphabet—the counts array takes constant space.