Блог пользователя SANYASI_RAJA

Автор SANYASI_RAJA, 15 месяцев назад, По-английски

Some of the most powerful techniques are also the simplest yet identifying when and how to apply them effectively can be challenging. Sliding window is one such method. Sliding window helps solve problems involving sequences, subarrays, or continuous segments by efficiently tracking changes as the window moves forward.

While tackling the CSES Sliding window problems, I noticed that many seemingly complex tasks like tracking the sum of elements in a dynamic segment, finding a subarray's minimum or maximum, or counting distinct elements can be simplified and optimized with this technique. Initially, one might consider brute-force methods iterating over every possible subarray or recomputing values from scratch. However, the core idea behind sliding window is smartly updating the state of the window rather than recalculating everything each time.

In my experience, the primary challenge while solving these problems came down to accurately managing the data structures supporting the window, as well as handling tricky edge cases involving modular arithmetic or negative values. Choosing the right DS such as monotonic deques for minimum or maximum queries, frequency maps for counting distinct elements, or multisets for median calculations.

A. Sliding Window Sum

Solution
Test Case
Code

B. Sliding Window Minimum

Prerequisites
Solution
Test Case
Code

C. Sliding Window Xor

Solution
Test Case
Code

D. Sliding Window Or

Solution
Test Case
Code

E. Sliding Window Distinct Values

Solution
Test Case
Code

F. Sliding Window Mode

Solution
Test Case
Code

G. Sliding Window Mex

Solution
Test Case
Code

H. Sliding Window Median

Prerequisites
Solution
Test Case
Code

I. Sliding Window Cost

Solution
Test Case
Code

J. Sliding Window Inversions

Prerequisites
Solution
Test Case
Code

K. Sliding Window Advertisement

Prerequisites
Solution
Test Case
Code
  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
8 месяцев назад, скрыть # |
← Rev. 3  
Проголосовать: нравится 0 Проголосовать: не нравится

For the Sliding Window Median problem, I think a cool approach that dont require a PBS can be:

Solution
Code
»
4 недели назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

I have another solution for the Sliding Window Median not usig a PBS:

Keep a sorted set $$$S$$$ of elements in the current window and an iterator pointing to the median element (&m, m is the median). When adding an $$$x$$$ and removing an element $$$y$$$:

  1. if $$$x \gt m$$$ and $$$y \lt m$$$ then $$$&m = next(&m)$$$
  2. if $$$x \lt m$$$ and $$$y \gt m$$$ then $$$&m = prev(&m)$$$
  3. otherwise the median doesn't change

it easy to prove that this ensures that &m always points to the median m.