1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
//! Keep track of the minimum or maximum value in a sliding window.
//!
//! `moving min max` provides one data structure for keeping track of the
//! minimum value and one for keeping track of the maximum value in a sliding
//! window.
//!
//! The algorithm is based on the description [here](https://stackoverflow.com/questions/4802038/implement-a-queue-in-which-push-rear-pop-front-and-get-min-are-all-consta).
//!
//! The complexity of the operations are
//! - O(1) for getting the minimum/maximum
//! - O(1) for push
//! - amortized O(1) for pop
//!
//! ```rust
//! use moving_min_max::MovingMin;
//!
//! let mut moving_min = MovingMin::<i32>::new();
//! moving_min.push(2);
//! moving_min.push(1);
//! moving_min.push(3);
//!
//! assert_eq!(moving_min.min(), Some(&1));
//! assert_eq!(moving_min.pop(), Some(2));
//!
//! assert_eq!(moving_min.min(), Some(&1));
//! assert_eq!(moving_min.pop(), Some(1));
//!
//! assert_eq!(moving_min.min(), Some(&3));
//! assert_eq!(moving_min.pop(), Some(3));
//!
//! assert_eq!(moving_min.min(), None);
//! assert_eq!(moving_min.pop(), None);
//! ```
//!
//! or
//!
//! ```rust
//! use moving_min_max::MovingMax;
//!
//! let mut moving_max = MovingMax::<i32>::new();
//! moving_max.push(2);
//! moving_max.push(3);
//! moving_max.push(1);
//!
//! assert_eq!(moving_max.max(), Some(&3));
//! assert_eq!(moving_max.pop(), Some(2));
//!
//! assert_eq!(moving_max.max(), Some(&3));
//! assert_eq!(moving_max.pop(), Some(3));
//!
//! assert_eq!(moving_max.max(), Some(&1));
//! assert_eq!(moving_max.pop(), Some(1));
//!
//! assert_eq!(moving_max.max(), None);
//! assert_eq!(moving_max.pop(), None);
//! ```

/// `MovingMin` provides O(1) access to the minimum of a sliding window.
#[derive(Debug)]
pub struct MovingMin<T> {
    push_stack: Vec<(T, T)>,
    pop_stack: Vec<(T, T)>,
}

impl<T: Clone + PartialOrd> Default for MovingMin<T> {
    fn default() -> Self {
        Self {
            push_stack: Vec::new(),
            pop_stack: Vec::new(),
        }
    }
}

impl<T: Clone + PartialOrd> MovingMin<T> {
    /// Creates a new `MovingMin` to keep track of the minimum in a sliding
    /// window.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new `MovingMin` to keep track of the minimum in a sliding
    /// window with `capacity` allocated slots.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            push_stack: Vec::with_capacity(capacity),
            pop_stack: Vec::with_capacity(capacity),
        }
    }

    /// Returns the minimum of the sliding window or `None` if the window is
    /// empty.
    #[inline]
    pub fn min(&self) -> Option<&T> {
        match (self.push_stack.last(), self.pop_stack.last()) {
            (None, None) => None,
            (Some((_, min)), None) => Some(min),
            (None, Some((_, min))) => Some(min),
            (Some((_, a)), Some((_, b))) => Some(if a < b { a } else { b }),
        }
    }

    /// Pushes a new element into the sliding window.
    #[inline]
    pub fn push(&mut self, val: T) {
        self.push_stack.push(match self.push_stack.last() {
            Some((_, min)) => {
                if val > *min {
                    (val, min.clone())
                } else {
                    (val.clone(), val)
                }
            }
            None => (val.clone(), val),
        });
    }

    /// Removes and returns the last value of the sliding window.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.pop_stack.is_empty() {
            match self.push_stack.pop() {
                Some((val, _)) => {
                    self.pop_stack.push((val.clone(), val));
                    while let Some((val, _)) = self.push_stack.pop() {
                        // This is safe, because we just pushed one element onto
                        // pop_stack and therefore it cannot be empty.
                        let last =
                            unsafe { self.pop_stack.get_unchecked(self.pop_stack.len() - 1) };
                        let min = if last.1 < val {
                            last.1.clone()
                        } else {
                            val.clone()
                        };
                        self.pop_stack.push((val.clone(), min));
                    }
                }
                None => return None,
            }
        }
        self.pop_stack.pop().map(|(val, _)| val)
    }

    /// Returns the number of elements stored in the sliding window.
    #[inline]
    pub fn len(&self) -> usize {
        self.push_stack.len() + self.pop_stack.len()
    }

    /// Returns `true` if the moving window contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// `MovingMax` provides O(1) access to the maximum of a sliding window.
#[derive(Debug)]
pub struct MovingMax<T> {
    push_stack: Vec<(T, T)>,
    pop_stack: Vec<(T, T)>,
}

impl<T: Clone + PartialOrd> Default for MovingMax<T> {
    fn default() -> Self {
        Self {
            push_stack: Vec::new(),
            pop_stack: Vec::new(),
        }
    }
}

impl<T: Clone + PartialOrd> MovingMax<T> {
    /// Creates a new `MovingMax` to keep track of the maximum in a sliding window.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new `MovingMax` to keep track of the maximum in a sliding window with
    /// `capacity` allocated slots.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            push_stack: Vec::with_capacity(capacity),
            pop_stack: Vec::with_capacity(capacity),
        }
    }

    /// Returns the maximum of the sliding window or `None` if the window is empty.
    #[inline]
    pub fn max(&self) -> Option<&T> {
        match (self.push_stack.last(), self.pop_stack.last()) {
            (None, None) => None,
            (Some((_, max)), None) => Some(max),
            (None, Some((_, max))) => Some(max),
            (Some((_, a)), Some((_, b))) => Some(if a > b { a } else { b }),
        }
    }

    /// Pushes a new element into the sliding window.
    #[inline]
    pub fn push(&mut self, val: T) {
        self.push_stack.push(match self.push_stack.last() {
            Some((_, max)) => {
                if val < *max {
                    (val, max.clone())
                } else {
                    (val.clone(), val)
                }
            }
            None => (val.clone(), val),
        });
    }

    /// Removes and returns the last value of the sliding window.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.pop_stack.is_empty() {
            match self.push_stack.pop() {
                Some((val, _)) => {
                    self.pop_stack.push((val.clone(), val));
                    while let Some((val, _)) = self.push_stack.pop() {
                        // This is safe, because we just pushed one element onto
                        // pop_stack and therefore it cannot be empty.
                        let last =
                            unsafe { self.pop_stack.get_unchecked(self.pop_stack.len() - 1) };
                        let max = if last.1 > val {
                            last.1.clone()
                        } else {
                            val.clone()
                        };
                        self.pop_stack.push((val.clone(), max));
                    }
                }
                None => return None,
            }
        }
        self.pop_stack.pop().map(|(val, _)| val)
    }

    /// Returns the number of elements stored in the sliding window.
    #[inline]
    pub fn len(&self) -> usize {
        self.push_stack.len() + self.pop_stack.len()
    }

    /// Returns `true` if the moving window contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn moving_min() {
        let mut moving_min = MovingMin::<i32>::new();
        moving_min.push(1);
        assert_eq!(moving_min.min(), Some(&1));
        moving_min.push(2);
        assert_eq!(moving_min.min(), Some(&1));
        moving_min.push(3);
        assert_eq!(moving_min.min(), Some(&1));
        assert_eq!(moving_min.pop(), Some(1));
        assert_eq!(moving_min.min(), Some(&2));
        assert_eq!(moving_min.pop(), Some(2));
        assert_eq!(moving_min.pop(), Some(3));
        assert_eq!(moving_min.pop(), None);

        moving_min.push(2);
        moving_min.push(1);
        moving_min.push(3);
        assert_eq!(moving_min.min(), Some(&1));
        assert_eq!(moving_min.pop(), Some(2));
        assert_eq!(moving_min.min(), Some(&1));
        assert_eq!(moving_min.pop(), Some(1));
        assert_eq!(moving_min.min(), Some(&3));
        assert_eq!(moving_min.pop(), Some(3));
        assert_eq!(moving_min.min(), None);
        assert_eq!(moving_min.pop(), None);
    }

    #[test]
    fn moving_max() {
        let mut moving_max = MovingMax::<i32>::new();
        moving_max.push(3);
        assert_eq!(moving_max.max(), Some(&3));
        moving_max.push(2);
        assert_eq!(moving_max.max(), Some(&3));
        moving_max.push(1);
        assert_eq!(moving_max.max(), Some(&3));
        assert_eq!(moving_max.pop(), Some(3));
        assert_eq!(moving_max.max(), Some(&2));
        assert_eq!(moving_max.pop(), Some(2));
        assert_eq!(moving_max.pop(), Some(1));
        assert_eq!(moving_max.pop(), None);

        moving_max.push(2);
        moving_max.push(3);
        moving_max.push(1);
        assert_eq!(moving_max.max(), Some(&3));
        assert_eq!(moving_max.pop(), Some(2));
        assert_eq!(moving_max.max(), Some(&3));
        assert_eq!(moving_max.pop(), Some(3));
        assert_eq!(moving_max.max(), Some(&1));
        assert_eq!(moving_max.pop(), Some(1));
        assert_eq!(moving_max.max(), None);
        assert_eq!(moving_max.pop(), None);
    }
}