Exactly one distinct rearrangement is sorted. Maintain the number of rearrangements of each prefix. When inserting element , let its new frequency be and update . Output . A prefix has no more rearrangements than the complete multiset, so . The multiplication is bounded by and fits signed 64-bit integers. Using a map gives time.