ENع
→Sliding window
الدرس 50 · Strings and problem-solving patterns

Sliding window

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة9 خطوات5 أسئلةAdvanced
عن هذا الدرس

Many problems ask for the best run of neighbouring items: the longest stretch, the largest sum of k numbers. A sliding window answers them in one pass. Watch a window slide over the string "abcbad": its right end takes in a new letter each step, and its left end lets letters go whenever one repeats, until it finds the longest substring with no repeated letter. The Software lessons "Strings: text in memory" and "Searching: linear and binary" cover indexing and lookup; "Two pointers" in this module is the same idea of two indices that only move forward.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 50 · تفاعلي
01 / 09

Longest run of different letters

Find the longest substring of s = "abcbad" with no repeated letter. The answer is 4, for "cbad". Checking every substring means n(n+1)/2 = 21 of them for six letters, and scanning 56 letters: O(n³) work.

s = "abcbad"   n = 6
goal: 4  ("cbad" = s[2:6])

brute force: for every start i and end j, check s[i..j] for a repeat
  substrings: n(n+1)/2 = 21
  letters scanned: n(n+1)(n+2)/6 = 56
  in general O(n³), or O(n²) with a set and an early stop
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Longest run of different letters

    Find the longest substring of s = "abcbad" with no repeated letter. The answer is 4, for "cbad". Checking every substring means n(n+1)/2 = 21 of them for six letters, and scanning 56 letters: O(n³) work.

    s = "abcbad"   n = 6
    goal: 4  ("cbad" = s[2:6])
    
    brute force: for every start i and end j, check s[i..j] for a repeat
      substrings: n(n+1)/2 = 21
      letters scanned: n(n+1)(n+2)/6 = 56
      in general O(n³), or O(n²) with a set and an early stop
  2. A window with two ends

    A window is a run of neighbouring letters, s[left..right]. Both ends start at 0. A set called seen holds the letters inside the window, so checking for a repeat is one quick lookup. best keeps the longest length so far.

    line 2  seen = set()          letters inside the window
    line 3  left = best = 0
    line 4  for right, ch in enumerate(s):   right = 0, 1, 2, ...
    
    the window is s[left..right], length right - left + 1
    rule: no letter twice inside the window
    `ch in seen` is O(1) on average for a Python set
  3. Grow to the right

    right moves to 0, 1, 2. The letters a, b and c are not in seen, so the while loop never runs. Each letter is added and the window grows. Its length reaches 3, so best = 3.

    right = 0, ch = 'a'
      line 5  'a' in seen → False
      line 8  seen.add('a')
      line 9  length 1, best = 1
    right = 1, ch = 'b'
      line 5  'b' in seen → False
      line 8  seen.add('b')
      line 9  length 2, best = 2
    right = 2, ch = 'c'
      line 5  'c' in seen → False
      line 8  seen.add('c')
      line 9  length 3, best = 3
    
    window s[0..2] = "abc"
    seen = {'a', 'b', 'c'}   best = 3
  4. A repeat: shrink from the left

    right = 3 brings a second b, and b is in seen. So left moves: remove a, left = 1. b is still there: remove b, left = 2. Now add the new b. The window is "cb"; best stays 3.

    right = 3, ch = 'b'
      line 5  'b' in seen → True
      line 6  seen.remove('a')
      line 7  left = 1
      line 5  'b' in seen → True
      line 6  seen.remove('b')
      line 7  left = 2
      line 5  'b' in seen → False
      line 8  seen.add('b')
      line 9  length 2, best = 3
    
    window s[2..3] = "cb"
    seen = {'c', 'b'}   best = 3
  5. An old letter comes back

    right = 4 brings a. The first a left the window a step ago, so it is not in seen any more. Add it. The window is "cba", length 3, so best stays 3.

    right = 4, ch = 'a'
      line 5  'a' in seen → False
      line 8  seen.add('a')
      line 9  length 3, best = 3
    
    window s[2..4] = "cba"
    seen = {'c', 'b', 'a'}   best = 3
  6. A new record

    right = 5 brings d, which is new. Add it. The window "cbad" runs from left = 2 to right = 5: length 5 - 2 + 1 = 4, more than 3, so best = 4.

    right = 5, ch = 'd'
      line 5  'd' in seen → False
      line 8  seen.add('d')
      line 9  length 4, best = 4
    
    window s[2..5] = "cbad"
    seen = {'c', 'b', 'a', 'd'}   best = 4
  7. The answer

    The loop ends and longest_unique returns 4, the length of "cbad" = s[2:6]. Brute force agrees, after checking all 21 substrings. The window looked at each letter at most twice: once as it entered and, maybe, once as it left.

    line 10  return best   4
    longest_unique("abcbad") == 4
    the window: s[2:6] = "cbad"
    brute force: best 4 after 21 substrings
  8. Why it is O(n)

    A while loop sits inside the for loop, yet both ends only move right. right moves n times and left at most n times. Here: 6 adds and 2 removes, at most 2n set changes. Each is O(1) on average, so the pass is O(n).

    adds:    6   (one per letter, as right moves)
    removes: 2   (at most one per letter, as left moves)
    total:   8 ≤ 2n = 12
    
    aggregate count (as in CLRS ch. 16): left never passes right,
    so the while loop runs at most n times over the whole scan
    set lookups, adds and removes: O(1) on average
    total: O(n) time, O(k) extra space for k different letters
  9. The pattern, in general

    Use a sliding window when the answer is a run of neighbours. Grow the right end; while a rule is broken, shrink the left end. A fixed-size window of k moves both ends together: add the item that enters, drop the one that leaves.

    variable window (this lesson):
      for right in range(n): add s[right]
          while the window breaks the rule: drop s[left]; left += 1
          record the window
    
    fixed window of k (for example the largest sum of k numbers):
      total += a[i] - a[i - k]     one add, one drop: O(n), not O(nk)
    
    it works when shrinking a bad window can only help,
    so left never needs to move back

اختبار يتاح بعد الخطوة الأخيرة.