Skip to content
Learn Netverks

Lesson

Step 11/36 31% through track

amortized-preview

Amortized complexity preview

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Amortized complexity preview: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Wrong complexity estimates ship slow APIs and fail interviews—analysis must precede micro-optimizations.

You will apply Amortized complexity preview in contexts like: Interview loops, performance tuning, and foundational CS courses.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

When you can explain the previous lesson's ideas in your own words.

Amortized analysis averages cost over a sequence of operations. std::vector::push_back is usually O(1) but occasionally O(n) when capacity doubles and elements copy—still O(1) amortized per push.

Intuition

  • Rare expensive resize pays for many cheap appends
  • Dynamic arrays double capacity → total copy work O(n) over n inserts
  • Hash table rehash — occasional O(n), average insert still O(1) amortized

Contrast with worst case

Interview clarity: state amortized for vector push_back; state worst-case O(n) for a single insert if resize happens that call.

Simulate growth

#include 
#include 

int main() {
    std::vector v;
    v.reserve(2);
    for (int i = 0; i < 6; ++i) {
        v.push_back(i);
        std::cout << "size=" << v.size() << " cap=" << v.capacity() << "\n";
    }
    return 0;
}

Important interview questions and answers

  1. Q: Amortized O(1) meaning?
    A: Average cost per operation over many ops stays constant even if some ops are expensive.
  2. Q: Why double capacity?
    A: Geometric growth keeps total copying O(n) for n appends.

Self-check

  1. Explain amortized analysis in one sentence.
  2. Why does vector capacity jump in steps?

Tip: push_back is amortized O(1)—mention rare resize when asked for precision.

Interview prep

Amortized meaning?

Average cost per op over sequence—vector push_back O(1) amortized.

Double capacity?

Keeps total copying O(n) over n inserts.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • vector push_back?
  • Amortized meaning?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump