Skip to content
Learn Netverks

Lesson

Step 14/36 39% through track

sliding-window

Sliding window

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

This lesson

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

These patterns turn O(n²) scans into O(n log n) or O(n)—core interview toolkit.

You will apply Sliding window 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.

A sliding window maintains a contiguous subarray/substring with two indices—expand right to grow, shrink left when constraint breaks. Ideal for max sum of length k or longest substring with at most k distinct chars.

Fixed window size k

Add new element at right, subtract leaving element at left—O(n) total.

Max sum of size 3

#include 
#include 

int main() {
    std::vector a = {2, 1, 5, 1, 3, 2};
    int k = 3, window = 0, best = 0;
    for (int i = 0; i < (int)a.size(); ++i) {
        window += a[i];
        if (i >= k) window -= a[i - k];
        if (i >= k - 1) best = std::max(best, window);
    }
    std::cout << "max sum k=3: " << best << "\n";
    return 0;
}

Variable window

Move left until valid (e.g. sum ≤ target), track best while valid—common in string problems.

Important interview questions and answers

  1. Q: Sliding window vs nested loops?
    A: Window moves each index once—O(n) vs O(n·k) or O(n²).
  2. Q: Fixed vs variable?
    A: Fixed k uses constant-size window; variable adjusts left based on constraint.

Self-check

  1. What is complexity of fixed-size sliding window on array length n?
  2. When do you subtract a[i-k] from the window?

Tip: Fixed window: add right, subtract left when i >= k.

Interview prep

Fixed window?

Add right, subtract element leaving window—O(n).

Use case?

Max/min sum subarray of size k, substring constraints.

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

  • Fixed vs variable?
  • Window invariant?

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