0
$\begingroup$

The circular buffer is filled with data one value at a time. The buffer size is N elements (let's take 3 as an example). Is there an algorithm that allows you to always know what is the minimum and maximum of the data in the buffer at a given time?

Example:

Initial samples: {3 4 3 1 5 2 7 3 4 1}
Step 1: {[3] 4 3 1 5 2 7 3 4 1} -> The max of [3] is 3.
Step 2: {[3, 4] 3 1 5 2 7 3 4 1} -> The max of [3 4] is 4.
Step 3: {[3 4 3] 1 5 2 7 3 4 1} -> The max of [3 4 3] is 4.
Step 4: {3 [4 3 1] 5 2 7 3 4 1} -> The max of [4 3 1] is 4.
Step 5: {3 4 [3 1 5] 2 7 3 4 1} -> The max of [3 1 5] is 5.
Step 6: {3 4 3 [1 5 2] 7 3 4 1} -> The max of [1 5 2] is 5.
Step 7: {3 4 3 1 [5 2 7] 3 4 1} -> The max of [5 2 7] is 7.
Step 8: {3 4 3 1 5 [2 7 3] 4 1} -> The max of [2 7 3] is 7.
Done.
The output is therefore {3, 4, 4, 4, 5, 5, 7, 7}.
asked Apr 29, 2023 at 7:27
$\endgroup$
2
  • 1
    $\begingroup$ What about [7 3 4] & [3 4 1]? $\endgroup$ Commented Apr 29, 2023 at 7:38
  • $\begingroup$ It is step 9 and 10 :) $\endgroup$ Commented May 1, 2023 at 7:55

1 Answer 1

1
$\begingroup$

Though you don't specify it, you probably mean in constant time (otherwise just compute the minimum and maximum in linear time). I don't think that this is possible.

There is a nice procedure to compute sliding window extrema, described in "Efficient Dilation, Erosion, Opening and Closing Algorithms" by Joseph Yossi Gil & Ron Kimmel. It takes no more than 3 comparisons per element, whatever $N$, and requires extra buffers.

Unfortunately, it can only deliver all results on every other $N$ elements.

If you allow $\log(n)$ behavior, a min-max heap can do.

answered Apr 29, 2023 at 8:57
$\endgroup$
2
  • $\begingroup$ Yes, i told about constant time, log also would be nice to reach. Can you please share some code sample in any languages? $\endgroup$ Commented May 1, 2023 at 7:56
  • $\begingroup$ Thirty seconds of Web lookup: github.com/d819r197/MinMax-Heap $\endgroup$ Commented May 1, 2023 at 18:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.