-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathavl_order_statistic_set.hpp
More file actions
878 lines (771 loc) · 23.5 KB
/
avl_order_statistic_set.hpp
File metadata and controls
878 lines (771 loc) · 23.5 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
#ifndef AVL_ORDER_STATISTIC_SET_HPP
#define AVL_ORDER_STATISTIC_SET_HPP
#include <algorithm>
#include <cstddef>
#include <functional>
#include <initializer_list>
#include <utility>
namespace avl_order_statistic_set {
/**
* @brief Node structure for AVL Order Statistic Tree
*
* @tparam T Type of elements stored in the node
*/
template <typename T> struct Node {
T key; ///< The key/value stored in the node
Node *left = nullptr; ///< Pointer to left child
Node *right = nullptr; ///< Pointer to right child
Node *parent = nullptr; ///< Pointer to parent node
int height = 1; ///< Height of the subtree rooted at this node
std::size_t size = 1; ///< Size of the subtree (for order statistics)
/**
* @brief Construct a new Node object (lvalue key version)
*
* @param value The key value to store
* @param p Pointer to parent node (default nullptr)
*/
explicit Node(const T &value, Node *p = nullptr) : key(value), parent(p) {}
/**
* @brief Construct a new Node object (rvalue key version)
*
* @param value The key value to store (will be moved)
* @param p Pointer to parent node (default nullptr)
*/
explicit Node(T &&value, Node *p = nullptr)
: key(std::move(value)), parent(p) {}
// Disallow copying
Node(const Node &) = delete;
Node &operator=(const Node &) = delete;
};
// ==================== UTILITY FUNCTIONS ====================
/**
* @brief Get the height of a node (nullptr-safe)
*
* @tparam T Type of node elements
* @param cur Node to check
* @return int Height of the node (0 if nullptr)
*/
template <typename T> int get_height(const Node<T> *cur) noexcept {
return cur ? cur->height : 0;
}
/**
* @brief Get the subtree size of a node (nullptr-safe)
*
* @tparam T Type of node elements
* @param cur Node to check
* @return std::size_t Size of subtree (0 if nullptr)
*/
template <typename T>
std::size_t get_subtree_size(const Node<T> *cur) noexcept {
return cur ? cur->size : 0;
}
/**
* @brief Calculate balance factor of a node
*
* @tparam T Type of node elements
* @param cur Node to check
* @return int Balance factor (left height - right height)
*/
template <typename T>
int calculate_balance_factor(const Node<T> *cur) noexcept {
return get_height(cur->left) - get_height(cur->right);
}
/**
* @brief Update node metadata (height and size)
*
* @tparam T Type of node elements
* @param cur Node to update
*/
template <typename T> void update_node_metadata(Node<T> *cur) noexcept {
if (cur) {
cur->height = 1 + std::max(get_height(cur->left), get_height(cur->right));
cur->size = 1 + get_subtree_size(cur->left) + get_subtree_size(cur->right);
}
}
// ==================== TREE ROTATIONS ====================
/**
* @brief Perform left rotation around a node
*
* @tparam T Type of node elements
* @param x The pivot node
* @return Node<T>* The new root of this subtree
*/
template <typename T> Node<T> *rotate_left(Node<T> *x) noexcept {
Node<T> *y = x->right;
x->right = y->left;
if (y->left)
y->left->parent = x;
y->parent = x->parent;
y->left = x;
x->parent = y;
update_node_metadata(x);
update_node_metadata(y);
return y;
}
/**
* @brief Perform right rotation around a node
*
* @tparam T Type of node elements
* @param y The pivot node
* @return Node<T>* The new root of this subtree
*/
template <typename T> Node<T> *rotate_right(Node<T> *y) noexcept {
Node<T> *x = y->left;
y->left = x->right;
if (x->right)
x->right->parent = y;
x->parent = y->parent;
x->right = y;
y->parent = x;
update_node_metadata(y);
update_node_metadata(x);
return x;
}
/**
* @brief Rebalance the tree at the given node if needed
*
* @tparam T Type of node elements
* @param cur Node to rebalance
* @return Node<T>* New root of the subtree after rebalancing
*/
template <typename T> Node<T> *rebalance(Node<T> *cur) noexcept {
update_node_metadata(cur);
int b = calculate_balance_factor(cur);
// Left heavy
if (b > 1) {
if (calculate_balance_factor(cur->left) < 0)
cur->left = rotate_left(cur->left);
cur = rotate_right(cur);
}
// Right heavy
else if (b < -1) {
if (calculate_balance_factor(cur->right) > 0)
cur->right = rotate_right(cur->right);
cur = rotate_left(cur);
}
update_node_metadata(cur);
return cur;
}
// ==================== TREE OPERATIONS ====================
/**
* @brief Find the node with minimum key in a subtree
*
* @tparam T Type of node elements
* @param cur Root of the subtree
* @return Node<T>* Pointer to minimum node
*/
template <typename T> Node<T> *find_min_node(Node<T> *cur) noexcept {
while (cur && cur->left)
cur = cur->left;
return cur;
}
/**
* @brief Find the node with maximum key in a subtree
*
* @tparam T Type of node elements
* @param cur Root of the subtree
* @return Node<T>* Pointer to maximum node
*/
template <typename T> Node<T> *find_max_node(Node<T> *cur) noexcept {
while (cur && cur->right)
cur = cur->right;
return cur;
}
/**
* @brief Recursively destroy a subtree
*
* @tparam T Type of node elements
* @param cur Root of the subtree to destroy
*/
template <typename T> void destroy(Node<T> *cur) noexcept {
if (cur) {
destroy(cur->left);
destroy(cur->right);
delete cur;
}
}
/**
* @brief Deep copy a subtree
*
* @tparam T Type of node elements
* @param src Root of source subtree
* @param parent Parent node for the new subtree
* @return Node<T>* Root of the new subtree
*/
template <typename T> Node<T> *deep_copy(Node<T> *src, Node<T> *parent) {
if (!src)
return nullptr;
Node<T> *n = new Node<T>(src->key, parent);
n->height = src->height;
n->size = src->size;
n->left = deep_copy(src->left, n);
n->right = deep_copy(src->right, n);
return n;
}
// ==================== ITERATOR TRAITS ====================
template <typename T> struct AVLOrderStatisticSetIteratorTraits {
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T *;
using reference = const T &;
};
// ==================== MAIN CLASS ====================
/**
* @brief AVL Tree based Order Statistic Set
*
* @tparam T Type of elements to store
* @tparam Compare Comparison function object type (default std::less<T>)
*
* This implementation provides:
* - O(log n) insertion, deletion and search
* - O(log n) order statistics operations
* - Full STL-style iterator support
* - Exception safety basic guarantee
*/
template <typename T, typename Compare = std::less<T>>
class AVLOrderStatisticSet {
Node<T> *root = nullptr; ///< Root of the AVL tree
std::size_t n = 0; ///< Number of elements in the set
Compare comp; ///< Comparison function object
// ==================== PRIVATE HELPERS ====================
/**
* @brief Find a node with given key
*
* @param cur Current node in search
* @param key Key to search for
* @return Node<T>* Pointer to found node or nullptr
*/
Node<T> *find_helper(Node<T> *cur, const T &key) const noexcept {
while (cur) {
if (comp(key, cur->key))
cur = cur->left;
else if (comp(cur->key, key))
cur = cur->right;
else
return cur;
}
return nullptr;
}
/**
* @brief Insert helper (lvalue key version) that returns both new root and
* inserted node
*
* @param cur Current node in recursion
* @param key Key to insert
* @param parent Parent node
* @param inserted [out] Set to true if insertion occurred
* @return std::pair<Node<T>*, Node<T>*> Pair of {new root, inserted node}
*/
std::pair<Node<T> *, Node<T> *>
insert_helper(Node<T> *cur, const T &key, Node<T> *parent, bool &inserted) {
if (!cur) {
Node<T> *nn = new Node<T>(key, parent);
inserted = true;
++n;
return {nn, nn};
}
Node<T> *inserted_node = nullptr;
if (comp(key, cur->key)) {
auto result = insert_helper(cur->left, key, cur, inserted);
cur->left = result.first;
inserted_node = result.second;
} else if (comp(cur->key, key)) {
auto result = insert_helper(cur->right, key, cur, inserted);
cur->right = result.first;
inserted_node = result.second;
} else {
// Key already exists, return current node as inserted node
inserted_node = cur;
}
return {rebalance(cur), inserted_node};
}
/**
* @brief Insert helper (rvalue key version) that returns both new root and
* inserted node
*
* @param cur Current node in recursion
* @param key Key to insert (will be moved)
* @param parent Parent node
* @param inserted [out] Set to true if insertion occurred
* @return std::pair<Node<T>*, Node<T>*> Pair of {new root, inserted node}
*/
std::pair<Node<T> *, Node<T> *>
insert_helper(Node<T> *cur, T &&key, Node<T> *parent, bool &inserted) {
if (!cur) {
Node<T> *nn = new Node<T>(std::forward<T>(key), parent);
inserted = true;
++n;
return {nn, nn};
}
Node<T> *inserted_node = nullptr;
if (comp(key, cur->key)) {
auto result =
insert_helper(cur->left, std::forward<T>(key), cur, inserted);
cur->left = result.first;
inserted_node = result.second;
} else if (comp(cur->key, key)) {
auto result =
insert_helper(cur->right, std::forward<T>(key), cur, inserted);
cur->right = result.first;
inserted_node = result.second;
} else {
// Key already exists, return current node as inserted node
inserted_node = cur;
}
return {rebalance(cur), inserted_node};
}
/**
* @brief Erase helper
*
* @param cur Current node in recursion
* @param key Key to erase
* @param erased [out] Set to true if erasure occurred
* @return Node<T>* New root of subtree
*/
Node<T> *erase_helper(Node<T> *cur, const T &key, bool &erased) {
if (!cur)
return nullptr;
if (comp(key, cur->key)) {
cur->left = erase_helper(cur->left, key, erased);
} else if (comp(cur->key, key)) {
cur->right = erase_helper(cur->right, key, erased);
} else {
// Actual deletion---set 'erased' and decrement n here ONLY
erased = true;
--n;
// Node with only one child or no child
if (!cur->left) {
Node<T> *right = cur->right;
if (right)
right->parent = cur->parent;
delete cur;
return right;
} else if (!cur->right) {
Node<T> *left = cur->left;
if (left)
left->parent = cur->parent;
delete cur;
return left;
}
// Node with two children
else {
Node<T> *y = find_min_node(cur->right);
cur->key = std::move(y->key);
bool dummy = false; // Don't double-count
cur->right = erase_helper(cur->right, cur->key, dummy);
}
}
return rebalance(cur);
}
/**
* @brief Erase a node given a direct pointer to the node (used for erasing by
* iterator).
*
* @tparam T Type of node elements
* @param cur The root of the subtree in which to find and erase the node
* @param to_delete Pointer to the node to erase
* @param erased [out] Set to true if erasure occurred
* @return Node<T>* New root of the subtree after erasure
*
* Removes the specified node from the tree and rebalances as necessary.
*/
Node<T> *erase_node_helper(Node<T> *cur, Node<T> *to_delete, bool &erased) {
if (!cur)
return nullptr;
if (cur == to_delete) {
// Actual deletion---set 'erased' and decrement n here ONLY
erased = true;
--n;
// Node with only one child or no child
if (!cur->left) {
Node<T> *right = cur->right;
if (right)
right->parent = cur->parent;
delete cur;
return right;
} else if (!cur->right) {
Node<T> *left = cur->left;
if (left)
left->parent = cur->parent;
delete cur;
return left;
}
// Node with two children
else {
Node<T> *y = find_min_node(cur->right);
cur->key = std::move(y->key);
bool dummy = false; // Don't double-count
cur->right = erase_helper(cur->right, cur->key, dummy);
}
} else if (comp(to_delete->key, cur->key)) {
cur->left = erase_node_helper(cur->left, to_delete, erased);
} else {
cur->right = erase_node_helper(cur->right, to_delete, erased);
}
return rebalance(cur);
}
public:
// ==================== CONSTRUCTORS/DESTRUCTOR ====================
/// Default constructor
AVLOrderStatisticSet() noexcept = default;
template <typename InputIt>
AVLOrderStatisticSet(InputIt first, InputIt last) {
for (; first != last; ++first)
insert(*first);
}
/**
* @brief Construct from initializer list
*
* @param il Initializer list of elements
*/
AVLOrderStatisticSet(std::initializer_list<T> il) {
for (const auto &v : il)
insert(v);
}
/// Move constructor
AVLOrderStatisticSet(AVLOrderStatisticSet<T, Compare> &&other) noexcept
: root(other.root), n(other.n), comp(std::move(other.comp)) {
other.root = nullptr;
other.n = 0;
}
/// Move assignment
AVLOrderStatisticSet<T, Compare> &
operator=(AVLOrderStatisticSet<T, Compare> &&other) noexcept {
if (this != &other) {
clear();
root = other.root;
n = other.n;
comp = std::move(other.comp);
other.root = nullptr;
other.n = 0;
}
return *this;
}
/// Copy constructor
AVLOrderStatisticSet(const AVLOrderStatisticSet<T, Compare> &other)
: n(other.n) {
root = deep_copy(other.root, nullptr);
}
/// Copy assignment
AVLOrderStatisticSet<T, Compare> &
operator=(const AVLOrderStatisticSet<T, Compare> &other) {
if (this != &other) {
clear();
n = other.n;
root = deep_copy(other.root, nullptr);
}
return *this;
}
/// Destructor
~AVLOrderStatisticSet() { clear(); }
// ==================== ITERATOR IMPLEMENTATION ====================
/**
* @brief Bidirectional iterator for AVLOrderStatisticSet
*/
class iterator {
Node<T> *node = nullptr; ///< Current node
const AVLOrderStatisticSet<T, Compare> *tree = nullptr; ///< Associated tree
iterator(Node<T> *n, const AVLOrderStatisticSet<T, Compare> *t)
: node(n), tree(t) {}
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T *;
using reference = const T &;
iterator() = default;
iterator(const iterator &) = default;
iterator &operator=(const iterator &) = default;
reference operator*() const { return node->key; }
pointer operator->() const { return &node->key; }
bool operator==(const iterator &other) const { return node == other.node; }
bool operator!=(const iterator &other) const { return node != other.node; }
/// Pre-increment (move to next larger key)
iterator &operator++() {
if (!node)
return *this;
if (node->right) {
node = find_min_node(node->right);
} else {
Node<T> *p = node->parent;
while (p && node == p->right) {
node = p;
p = p->parent;
}
node = p;
}
return *this;
}
/// Post-increment
iterator operator++(int) {
iterator tmp(*this);
++(*this);
return tmp;
}
/// Pre-decrement (move to next smaller key)
iterator &operator--() {
if (!node) {
node = find_max_node(tree->root);
} else if (node->left) {
node = find_max_node(node->left);
} else {
Node<T> *p = node->parent;
while (p && node == p->left) {
node = p;
p = p->parent;
}
node = p;
}
return *this;
}
/// Post-decrement
iterator operator--(int) {
iterator tmp(*this);
--(*this);
return tmp;
}
friend class AVLOrderStatisticSet;
};
// Iterator type aliases
using reverse_iterator = std::reverse_iterator<iterator>;
using const_iterator = iterator;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// ==================== ITERATOR ACCESS ====================
iterator begin() const { return iterator(find_min_node(root), this); }
iterator end() const { return iterator(nullptr, this); }
reverse_iterator rbegin() const { return reverse_iterator(end()); }
reverse_iterator rend() const { return reverse_iterator(begin()); }
const_iterator cbegin() const { return begin(); }
const_iterator cend() const { return end(); }
const_reverse_iterator crbegin() const {
return const_reverse_iterator(cend());
}
const_reverse_iterator crend() const {
return const_reverse_iterator(cbegin());
}
friend iterator begin(const AVLOrderStatisticSet<T, Compare> &s) {
return s.begin();
}
friend iterator end(const AVLOrderStatisticSet<T, Compare> &s) {
return s.end();
}
// ==================== EQUALITY ====================
/**
* @brief Checks if two AVLOrderStatisticSets are equal
*
* Two sets are considered equal if they contain the same elements.
* This is determined by:
* 1. Comparing sizes (must be equal)
* 2. Comparing elements in order (since sets are ordered)
*
* @param other The set to compare with
* @return true If both sets contain exactly the same elements
* @return false If sets differ in size or element content
*/
bool operator==(const AVLOrderStatisticSet<T, Compare> &other) const {
return size() == other.size() && std::equal(begin(), end(), other.begin());
}
// ==================== CAPACITY ====================
std::size_t size() const noexcept { return n; }
bool empty() const noexcept { return n == 0; }
explicit operator bool() const noexcept { return !empty(); }
// ==================== MODIFIERS ====================
/// Clear all elements from the set
void clear() noexcept {
destroy(root);
root = nullptr;
n = 0;
}
/**
* @brief Insert a key (lvalue version)
*
* @param key Key to insert
* @return std::pair<iterator, bool> Iterator to inserted element and success
* flag
*/
std::pair<iterator, bool> insert(const T &key) {
bool inserted = false;
auto result = insert_helper(root, key, nullptr, inserted);
root = result.first;
return {iterator(result.second, this), inserted};
}
/**
* @brief Insert a key (rvalue version)
*
* @param key Key to insert (will be moved)
* @return std::pair<iterator, bool> Iterator to inserted element and success
* flag
*/
std::pair<iterator, bool> insert(T &&key) {
bool inserted = false;
auto result = insert_helper(root, std::move(key), nullptr, inserted);
root = result.first;
return {iterator(result.second, this), inserted};
}
/**
* @brief Constructs element in-place if the key doesn't exist
*
* @tparam Args Types of arguments to construct the element
* @param args Arguments to forward to the constructor of the element
* @return std::pair<iterator, bool>
* pair::first: Iterator to the inserted element or the element that
* prevented insertion pair::second: true if insertion occurred, false
* otherwise
*/
template <typename... Args>
std::pair<iterator, bool> emplace(Args &&...args) {
T key(std::forward<Args>(args)...);
return insert(std::move(key));
}
/**
* @brief Erases element with the specified key if it exists
*
* @param key Key of the element to erase
* @return std::size_t Number of elements erased (0 or 1)
*/
std::size_t erase(const T &key) {
bool erased = false;
root = erase_helper(root, key, erased);
return erased ? 1 : 0;
}
/**
* @brief Erase by iterator: returns iterator to next element
*
* @param pos Iterator of the element to erase
* @return iterator Iterator to next element
*/
iterator erase(iterator pos) {
if (pos == end())
return end();
Node<T> *del_node = pos.node;
iterator next = pos;
++next;
bool erased = false;
root = erase_node_helper(root, del_node, erased);
return next;
}
/**
* @brief Swaps the contents of this set with another.
*
* @param other The other AVLOrderStatisticSet to swap with
*
* Swaps the roots, element counts, and comparison functors of the two sets.
*/
void swap(AVLOrderStatisticSet<T, Compare> &other) noexcept {
std::swap(root, other.root);
std::swap(n, other.n);
std::swap(comp, other.comp);
}
// ==================== LOOKUP ====================
/**
* @brief Finds an element with key equivalent to key
*
* @param key Key value to search for
* @return iterator Iterator to the found element, or end() if not found
*/
iterator find(const T &key) const {
return iterator(find_helper(root, key), this);
}
/**
* @brief Returns the number of elements with key equivalent to key
*
* @param key Key value to count
* @return std::size_t 1 if the container contains the key, 0 otherwise
*
* Since this is a set, the count will always be 0 or 1
*/
std::size_t count(const T &key) const {
return find_helper(root, key) ? 1 : 0;
}
/**
* @brief Finds an iterator to the first element not less than (i.e. greater
* or equal to) the specified key.
*
* @param key The key to compare against
* @return iterator Iterator to the first element that is not less than key,
* or end() if every element in the set is less than key.
*
* Complexity: O(log n)
*/
iterator lower_bound(const T &key) const {
Node<T> *cur = root, *res = nullptr;
while (cur) {
if (!comp(cur->key, key)) {
res = cur;
cur = cur->left;
} else
cur = cur->right;
}
return iterator(res, this);
}
/**
* @brief Finds an iterator to the first element greater than the specified
* key.
*
* @param key The key to compare against
* @return iterator Iterator to the first element that is greater than key,
* or end() if no such element exists.
*
* Complexity: O(log n)
*/
iterator upper_bound(const T &key) const {
Node<T> *cur = root, *res = nullptr;
while (cur) {
if (comp(key, cur->key)) {
res = cur;
cur = cur->left;
} else
cur = cur->right;
}
return iterator(res, this);
}
// ==================== ORDER STATISTICS ====================
/**
* @brief Finds the element at the specified position in the sorted sequence
*
* @param k 0-based index of the element to find
* @return iterator Iterator to the element at position k, or end() if k >=
* size()
*
* Complexity: O(log n)
*/
iterator find_by_order(std::size_t k) const {
Node<T> *cur = root;
while (cur) {
std::size_t left_sz = get_subtree_size(cur->left);
if (k < left_sz)
cur = cur->left;
else if (k > left_sz) {
k -= left_sz + 1;
cur = cur->right;
} else {
return iterator(cur, this);
}
}
return end(); // not found, k >= size()
}
/**
* @brief Returns the number of elements with keys less than key
*
* @param key Key to compare against
* @return std::size_t Number of elements with keys less than key
*
* Complexity: O(log n)
*/
std::size_t order_of_key(const T &key) const {
std::size_t res = 0;
Node<T> *cur = root;
while (cur) {
if (comp(cur->key, key)) {
res += get_subtree_size(cur->left) + 1;
cur = cur->right;
} else {
cur = cur->left;
}
}
return res;
}
};
} // namespace avl_order_statistic_set
#endif // AVL_ORDER_STATISTIC_SET_HPP