AI EducademyAIEducademy
🌳

AI基础

🌱
AI 种子

从零开始

🌿
AI 萌芽

打好基础

🌳
AI 枝干

付诸实践

🏕️
AI 树冠

深入探索

🌲
AI 森林

精通AI

🔨

AI精通

✏️
AI 草图

从零开始

🪨
AI 雕刻

打好基础

⚒️
AI 匠心

付诸实践

💎
AI 打磨

深入探索

🏆
AI 杰作

精通AI

🚀

职业准备

🚀
面试发射台

开启你的旅程

🌟
行为面试精通

掌握软技能

💻
技术面试

通过编程轮次

🤖
AI与ML面试

ML面试精通

🏆
Offer与未来

拿下最好的Offer

查看所有学习计划→

实验室

已加载 7 个实验
🧠神经网络游乐场🤖AI 还是人类?💬提示实验室🎨图像生成器😊情感分析器💡聊天机器人构建器⚖️伦理模拟器
🎯模拟面试进入实验室→
学习旅程博客
🎯
关于

让AI教育触达每一个人、每一个角落

❓
常见问题

Common questions answered

✉️
Contact

Get in touch with us

⭐
Open Source

在 GitHub 上公开构建

立即开始
AI EducademyAIEducademy

MIT 许可证。开源项目

学习

  • 学习计划
  • 课程
  • 实验室

社区

  • GitHub
  • 参与贡献
  • 行为准则
  • 关于
  • 常见问题

支持

  • 请我喝杯咖啡 ☕
  • 服务条款
  • 隐私政策
  • 联系我们
AI & 工程学习计划›🪨 AI 雕刻›课程›双指针与滑动窗口
👆
AI 雕刻 • 中级⏱️ 15 分钟阅读

双指针与滑动窗口

Why Scanning Smartly Matters

Imagine an AI monitoring a live video feed for suspicious activity. It cannot rewatch the entire recording every second - it needs to slide a window of attention across the stream, keeping track of just enough context. That is exactly what the two pointers and sliding window patterns do for sequential data.

Both techniques turn brute-force O(n²) scans into elegant O(n) passes.

Two pointers converging from both ends of an array and a sliding window moving across a data stream
Two pointers shrink the search space; a sliding window maintains a running view.

The Two Pointer Technique

Place two references into a sequence and move them according to a rule. There are two main flavours.

Converging Pointers

Start one pointer at each end and move them inward. Perfect for sorted data.

Classic problem - Pair Sum: Given a sorted array, find two numbers that add to a target.

function pairSum(arr, target):
    left = 0
    right = arr.length - 1
    while left < right:
        sum = arr[left] + arr[right]
        if sum == target: return (left, right)
        if sum < target: left += 1
        else: right -= 1
    return null

Because the array is sorted, moving left right increases the sum, and moving right left decreases it - guaranteeing we never miss a valid pair.

Same-Direction Pointers

Both pointers move forward, but at different speeds. Useful for partitioning or cycle detection.

Example - Remove duplicates in-place: A slow pointer marks the write position; a fast pointer scans ahead.

function removeDuplicates(arr):
    slow = 0
    for fast in 1..arr.length - 1:
        if arr[fast] != arr[slow]:
            slow += 1
            arr[slow] = arr[fast]
    return slow + 1
🧠小测验

In the converging two-pointer technique on a sorted array, what should you do when the current sum is less than the target?

第 1 课,共 10 课已完成 0%
←返回学习计划

Discussion

Sign in to join the discussion

建议修改本课内容

The Sliding Window Pattern

A sliding window maintains a contiguous sub-sequence of size k (fixed) or variable length, updating aggregates incrementally instead of recalculating from scratch.

Fixed-Size Window

Slide a window of exactly k elements across the array.

Example - Maximum sum of any k consecutive elements:

function maxSubarraySum(arr, k):
    windowSum = sum(arr[0..k-1])
    best = windowSum
    for i in k..arr.length - 1:
        windowSum += arr[i] - arr[i - k]
        best = max(best, windowSum)
    return best

Each step adds the new element entering the window and subtracts the one leaving - O(1) per move.

Variable-Size Window

Expand the window to include more data, then shrink it when a constraint is violated.

Example - Longest substring without repeating characters:

function longestUnique(s):
    seen = {}
    left = 0
    best = 0
    for right in 0..s.length - 1:
        if s[right] in seen and seen[s[right]] >= left:
            left = seen[s[right]] + 1
        seen[s[right]] = right
        best = max(best, right - left + 1)
    return best
🤯
Streaming analytics platforms like Apache Flink use sliding and tumbling windows as first-class primitives - the same concept scaled to millions of events per second.

Real AI Applications

| Pattern | AI Use Case | |---------|------------| | Fixed window | Anomaly detection over the last k sensor readings | | Variable window | Finding the shortest text span containing all query keywords (search engines) | | Converging pointers | Efficient nearest-neighbour checks in sorted embedding dimensions | | Same-direction pointers | Merging sorted result lists from multiple retrieval models |

🤔
Think about it:A voice assistant buffers the last 3 seconds of audio to detect a wake word. Which pattern is this - fixed window or variable window? What happens if the wake word is longer than the buffer?

When to Use Which

  • Two pointers (converging): sorted input, pair/triplet search, palindrome checks.
  • Two pointers (same-direction): in-place modifications, fast/slow runner problems.
  • Fixed sliding window: aggregate over a known window size.
  • Variable sliding window: find the smallest or largest window satisfying a condition.
🧠小测验

Which pattern would you choose to find the smallest subarray whose sum exceeds a given value?

🤔
Think about it:Could you combine two pointers with a sliding window? Think about problems where you need to find a pair within a rolling window of data - for instance, detecting duplicate transactions within a five-minute window.

Key Takeaways

  1. Two pointers eliminate nested loops by leveraging ordering or partitioning.
  2. Sliding windows maintain running state so each element is processed at most twice.
  3. Both patterns are foundational in real-time AI pipelines - from anomaly detection to search ranking.
🧠小测验

What is the typical time complexity achieved by converting a brute-force nested loop into a two-pointer or sliding-window solution?