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

Greedy algorithms docs
Greedy algorithms
Greedy ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Discussions

Greedy algorithms guide · 4/6

Complexity

The cost of a greedy algorithm usually comes from sorting or priority-queue operations; the choice itself is often constant time per candidate. That is why the classic greedy algorithms typically run in O(n log n), dropping to O(n) when the input is already sorted.

Complexity by problem

ProblemGreedy ruleTimeExtra space
Interval schedulingearliest endO(n log n)O(n) (sorted copy)
Activity selection (already sorted by end)sameO(n)O(1)
Huffman codingmerge the two lightestO(n log n)O(n)
Huffman (sorted frequencies)two queuesO(n)O(n)
Fractional knapsackhighest value per weightO(n log n)O(n)
Meeting roomsby start + min-heap of endsO(n log n)O(n)

Best, average and worst cases barely differ. Sorting costs O(n log n) regardless of input shape (Python's Timsort drops to O(n) on already sorted data), and the scan that follows is always a single pass. In the meeting-room algorithm the heap never holds more than k entries, the maximum number of simultaneous meetings, so the tighter bound is O(n log k).

Linear-time Huffman with two queues

When frequencies are already sorted ascending, you can compute the Huffman cost with two queues and no heap. Merged weights come out in non-decreasing order, so the second queue stays sorted by itself.

from collections import deque


def huffman_cost_sorted(weights):
    """Total encoded bits for ascending weights, in O(n)."""
    leaves, merged = deque(weights), deque()

    def pop_min():
        if not merged or (leaves and leaves[0] <= merged[0]):
            return leaves.popleft()
        return merged.popleft()

    total = 0
    while len(leaves) + len(merged) > 1:
        a = pop_min()
        b = pop_min()
        total += a + b
        merged.append(a + b)
    return total


print(huffman_cost_sorted([5, 9, 12, 13, 16, 45]))  # 224

Counting rooms without a heap

If you only need the number of rooms, sort start and end times separately and sweep with two pointers. It is still O(n log n), but with smaller constants and less code. It does not tell you which meeting goes in which room, so use the heap version when you need the assignment.

def min_rooms_sweep(meetings):
    starts = sorted(s for s, _ in meetings)
    ends = sorted(e for _, e in meetings)
    rooms = j = 0
    for s in starts:
        if ends[j] <= s:
            j += 1      # inherit the room of a meeting that has ended
        else:
            rooms += 1  # open another room
    return rooms


print(min_rooms_sweep([(9, 10), (9, 12), (10, 11), (11, 13), (12, 13)]))  # 2

Compared with alternatives

ProblemGreedyAlternativeNote
Max number of intervalsoptimal, O(n log n)brute force O(2^n · n)greedy is exact
Weighted intervalsnot optimalDP + binary search O(n log n)greedy fails once values differ
Fractional knapsackoptimal, O(n log n)linear programminggreedy is exact
0/1 knapsacknot optimalDP O(nW)W is the capacity
Change, canonical coinsoptimal, O(k)DP O(k · amount)k coin types
Change, arbitrary coinsnot optimalDP O(k · amount)coins 1, 3, 4

Where greedy is correct it beats the alternatives on both time and memory. But small changes to the problem (adding weights, making items indivisible) take the guarantee away. When the problem changes, re-check correctness before you worry about complexity.

Measure it yourself

You can check the theory against wall-clock time. If time grows a bit more than tenfold when n grows tenfold, that matches O(n log n).

import random
import time


def max_count(intervals):
    count, last_end = 0, float("-inf")
    for start, end in sorted(intervals, key=lambda iv: iv[1]):
        if start >= last_end:
            count, last_end = count + 1, end
    return count


for n in (10_000, 100_000, 1_000_000):
    data = [(s, s + random.randint(1, 100)) for s in (random.randint(0, 10**6) for _ in range(n))]
    t = time.perf_counter()
    max_count(data)
    print(n, f"{time.perf_counter() - t:.3f}s")

Summary

  • Greedy running time is dominated by sorting or heap operations and is usually O(n log n).
  • With pre-sorted input, both activity selection and Huffman coding drop to O(n).
  • Use the two-pointer sweep when you only need a room count, the heap when you need the assignment.
  • Greedy is the fastest option when it is correct, but weights or indivisible items call for dynamic programming.
Questions about this chapter?
Previous chapterImplementationNext chapterPractice Problems

0 comments

Top commentsNewest first

Sign in · Sign in to leave a comment.