Skip to main content
ProductsDesktop toolsTASTECADDrawing reviewTASTEFILESFile managementTASTEFTPFile transferTASTESSHRemote workspaceTASTEZIPCompression and extractionTASTEWINMFile managementDeveloper toolsTASTECODERust integrated development environmentTASTESTUDIOIntegrated development and test environmentTASTEETLData integration (ETL)ServersTASTEREMOTERemote desktop serverTASTEGEOGeospatial serverTASTEMAILMail workspaceInvestingTASTESTOCKStock auto-trading desktop appGet startedDownloadsDocumentationBuyAll products
Marketplace
News
TechNewsToday's dev newsDeveloper docsProgramming languagesRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngularServer frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressApp & desktop frameworksTauriFlutterReact NativeElectronAlgorithmsAlgorithm basicsCore algorithmsAdvanced algorithmsPractical algorithms
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcaseCommunity guide
Work with usTech transferWebsite buildDesktop app buildRelease and payment pipelineSales partnerContact
ServicesRemote desktopCustom installer packages
TASTEDEV
Products

Desktop tools

TASTECADComplex drawings, opened with easeTASTEFILESJust the files you need, as fast as possibleTASTEFTPThe tidiest path for your filesTASTESSHA stronger link between you and your serversTASTEZIPPack faster, unpack saferTASTEWINMA keyboard-first file manager with two panes

Developer tools

TASTECODEEdit, build, debug and test Rust apps in one windowTASTESTUDIOFrom editing to remote tests and approved AI fixesTASTEETLMove data while you watch the values

Servers

TASTEREMOTEA remote desktop you run on your own serverTASTEGEORebuilding a GeoServer-compatible geospatial server in RustTASTEMAILTake back control of your email

Investing

TASTESTOCKStock auto-trading that follows the rules you set: when, and what

Get started

DownloadsLatest builds of every productDocsHow to use each productBuySubscriptions and perpetual licencesAll productsEvery product at a glance
All products
MarketplaceNews
Tech

News

Today's dev newsOfficial announcements on languages, frameworks, GitHub and AIDeveloper docsGuides to languages, frameworks and algorithms

Programming languages

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Web front-end frameworksNext.jsReactVue.js · NuxtSvelteKitAngular
Server frameworksSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
App & desktop frameworksTauriFlutterReact NativeElectron

Algorithms

Algorithm basicsComplexity analysis · Sorting · Searching · Basic data structures · Trees and heapsCore algorithmsGraph traversal · Shortest paths & minimum spanning trees · Dynamic programming · Greedy algorithms · Divide and conquer · BacktrackingAdvanced algorithmsString algorithms · Math and number theory · Bit manipulation · Segment trees · Union-findPractical algorithmsCoding interview strategy · LRU cache · Rate limiting · Consistent hashing
All development docs
Community
ProjectsDiscover builders and their workDevelopment logsDecisions and lessons learnedPromptsReusable instructionsAI tool issuesProblems and workarounds for Claude, Codex, GeminiShowcaseFinished resultsCommunity guideHow we build in the open
Work with us
Tech transferNative apps in Rust and eguiWebsite build10 languages, accounts, docs and downloadsDesktop app buildRust and egui, no WebViewRelease and payment pipelineSigning, MSI, deb, rpm, AppImage, hashesSales partnerRecommend us and earn 30%ContactBuilds, partnerships and investment
Services
Remote desktopReach your computer from a browserCustom installer packagesOnly the features you need, settings preloaded
Buy
EN
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Log in
Log in
TASTEDEV

From small tools to better development.

support@tastedev.netSupport TASTEDEV
ProductsProduct lineupBuyDocsDownloadsMarketplaceSupport
CommunityProjectsDevelopment logsPromptsAI tool issuesShowcase
PoliciesAbout usPrivacy policyTerms of serviceSubscription termsRefund policyCommunity guidelines
AccountLog inSign up
Visitors
Today
Yesterday
Total views
Company
GXSOFT
Representative
CHOI YOUNG GU
Business registration number
853-44-00368
Address
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Phone
+82-10-4404-1523
Email
whitecalvin@tastedev.net
Privacy officer
CHOI YOUNG GU

© 2026 TASTEDEVProduct information is based on verified development sources.Released · improving

Sorting docs
Sorting
Sorting ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussions

Sorting guide · 5/6

Practice Problems

Most sorting problems are not "implement a sort" but "sort first, then the rest is easy". The four problems below practice sort-then-scan, multi-key ordering, custom comparators and reusing the merge step. Try each one before reading the solution.

Problem 1. Merge room bookings

Room bookings are given as (start, end) pairs of integers in no particular order. Merge bookings that overlap or touch, and return the periods when the room is actually in use, ordered by start time. For [(9, 11), (13, 15), (10, 12), (15, 16)] the answer is [[9, 12], [13, 16]].

Approach: after sorting by start time, a booking can only overlap the last merged period. Scan in order; if the current start is at most the last end, extend that end, otherwise open a new period. Sorting costs O(n log n) and the scan O(n).

def merge_bookings(bookings):
    result = []
    for start, end in sorted(bookings):
        if result and start <= result[-1][1]:
            result[-1][1] = max(result[-1][1], end)
        else:
            result.append([start, end])
    return result

print(merge_bookings([(9, 11), (13, 15), (10, 12), (15, 16)]))  # [[9, 12], [13, 16]]

Problem 2. Contest leaderboard

Each contestant has (name, score, seconds). Rank by score descending, then by time ascending, then by name alphabetically.

Approach: one tuple key expresses all three criteria, and negating the numeric score turns it into descending order. If a criterion that cannot be negated (such as a string) must be descending, run several stable sorts from the least to the most significant criterion. Python's reverse=True preserves stability too.

players = [("lee", 90, 300), ("kim", 95, 410), ("park", 90, 280), ("choi", 90, 300)]

ranked = sorted(players, key=lambda p: (-p[1], p[2], p[0]))
print([p[0] for p in ranked])  # ['kim', 'park', 'choi', 'lee']

# The same result with repeated stable sorts, least significant key first
step = sorted(players, key=lambda p: p[0])
step = sorted(step, key=lambda p: p[2])
step = sorted(step, key=lambda p: p[1], reverse=True)
print([p[0] for p in step])    # ['kim', 'park', 'choi', 'lee']

Problem 3. Largest concatenated number

Given non-negative integers, arrange them so that their concatenation is the largest possible number, and return it as a string. For [3, 30, 34, 5, 9] the answer is "9534330". If all values are zero, return "0".

Approach: sorting numerically or lexicographically fails on pairs like 3 and 30. Instead compare two strings a and b by whichever of a + b and b + a is larger. This comparison is transitive, so it is a valid sort order. Strip leading zeros so that "000" becomes "0".

from functools import cmp_to_key

def largest_number(nums):
    words = [str(n) for n in nums]

    def compare(a, b):
        if a + b > b + a:
            return -1   # a goes first
        if a + b < b + a:
            return 1
        return 0

    words.sort(key=cmp_to_key(compare))
    return "".join(words).lstrip("0") or "0"

print(largest_number([3, 30, 34, 5, 9]))  # 9534330
print(largest_number([0, 0]))             # 0

Problem 4. Count out-of-order pairs

Count the pairs i < j with a[i] > a[j] (inversions) in an integer array of up to 200,000 elements. For example, [3, 1, 2] has two: (3, 1) and (3, 2).

Approach: checking every pair is O(n²), far too slow. During the merge step of merge sort, when right[j] is taken, the len(left) - i elements still waiting on the left are all larger and originally came earlier, so each forms an inversion. Adding these counts yields the answer in O(n log n) while sorting.

def count_inversions(a):
    def solve(items):
        if len(items) <= 1:
            return items, 0
        mid = len(items) // 2
        left, x = solve(items[:mid])
        right, y = solve(items[mid:])
        merged, i, j, cross = [], 0, 0, 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                j += 1
                cross += len(left) - i
        merged += left[i:] + right[j:]
        return merged, x + y + cross

    return solve(list(a))[1]

print(count_inversions([3, 1, 2]))        # 2
print(count_inversions([5, 4, 3, 2, 1]))  # 10

Equal values are not inversions, so the left element must be taken on ties (<=). Using < would count equal pairs by mistake.

Summary

  • Interval problems usually start with "sort by start, then scan once".
  • Use tuple keys for multiple criteria, and repeated stable sorts when a criterion cannot be negated.
  • Custom comparators work only when they are consistent (transitive).
  • The merge step of merge sort is a tool for counting order relations such as inversions.
Questions about this chapter?
Previous chapterComplexityNext chapterReal-World Use

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.