Skip to content
Learn Netverks

Lesson

Step 7/36 19% through track

time-complexity

Time complexity

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Time complexity: 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 Time complexity in contexts like: API design reviews, capacity planning, and whiteboard interview loops.

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.

Time complexity counts primitive operations as a function of input size. One pass over a vector is O(n); binary search on sorted data is O(log n).

Examples

  • Access v[i] — O(1)
  • Linear search unsorted data — O(n)
  • std::sort — O(n log n) typical
  • Check all pairs — O(n²)

Hidden costs

std::vector::insert in the middle shifts elements—O(n). push_back amortized O(1). Know your container operations.

Binary search steps

#include 
#include 

int main() {
    std::vector a = {2, 5, 8, 12, 16};
    int target = 12;
    int lo = 0, hi = (int)a.size() - 1, steps = 0;
    while (lo <= hi) {
        ++steps;
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == target) break;
        if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    std::cout << "steps=" << steps << " (O(log n))\n";
    return 0;
}

Important interview questions and answers

  1. Q: Why mid = lo + (hi-lo)/2?
    A: Avoids overflow from (lo+hi)/2 and is standard interview style.
  2. Q: Is sort always O(n log n)?
    A: Comparison sorts are; counting sort can be O(n) with constraints on value range.

Self-check

  1. What is time complexity of linear search?
  2. What is time complexity of binary search on sorted array?

Pitfall: vector::insert in the middle is O(n)—not O(1) like push_back amortized.

Interview prep

Binary search time?

O(log n) on sorted data.

std::sort?

O(n log n) comparison sort typical.

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

  • Binary search time?
  • Sort typical?

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