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

Swap Two Elements

Back to problem

Editorial

Consider the inversion count of the permutation. Let the two values actually swapped by an operation be x<yx<yx<y. Since they are the smallest and second-smallest values in the chosen interval, every value between their positions is greater than yyy. Therefore, the total number of inversions involving these intermediate values and x,yx,yx,y is unchanged by the swap; only the inversion relation between xxx and yyy changes. Thus one operation changes the total inversion count by exactly 111, either increasing or decreasing it. Sorting must eliminate every inversion, so at least the initial number of inversions is necessary.

If the chosen interval has length two, its two elements are automatically the smallest and the second-smallest values in that interval. Thus the operation is exactly an adjacent swap. Bubble sort swaps adjacent inverted pairs one by one; every such swap decreases the inversion count by exactly one and eventually sorts the permutation.

Hence bubble sort uses the minimum possible number of operations. Its running time is O(N2)O(N^2)O(N2), and at most N(N−1)/2N(N-1)/2N(N−1)/2 operations are printed. Solution written by GPT5.6