DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord account linking.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Unsorting a Sequence 2

Back to problem

Editorial

Exactly one distinct rearrangement is sorted. Maintain the number WWW of rearrangements of each prefix. When inserting element iii, let its new frequency be ccc and update W←W⋅i/cW\leftarrow W\cdot i/cW←W⋅i/c. Output W−1W-1W−1. A prefix has no more rearrangements than the complete multiset, so W≤1012+1W\leq10^{12}+1W≤1012+1. The multiplication is bounded by (1012+1)105<1.01⋅1017(10^{12}+1)10^5<1.01\cdot10^{17}(1012+1)105<1.01⋅1017 and fits signed 64-bit integers. Using a map gives O(Nlog⁡N)O(N\log N)O(NlogN) time.