Given an array of integers with limited range (0 to 1000000). We need to implement an Order statistic tree using fenwick tree.
It should support four operations: Insert, Delete, Select and Rank. Here n denotes the size of Fenwick tree and q denotes number of queries.
Each query should be one of the following 4 operations.
- insertElement(x) – Insert element x into Fenwick tree, with O(log n) worst case time complexity
- deleteElement(x) – Delete element x from fenwick tree, with O(log n) worse case time complexity
- findKthSmallest(k) – Find the k-th smallest element stored in the tree, with O(log n * log n) worst case time complexity
- findRank(x) – Find the rank of element x in the tree, i.e. its index in the sorted list of elements of the tree, with O(log n) time complexity
Prerequisite : Binary Indexed Tree or Fenwick Tree
The idea is to create a BIT of size with maximum limit. We insert an element in BIT using it as an index. When we insert an element x, we increment values of all ancestors of x by 1. To delete an element, we decrement values of ancestors by 1. We basically call standard function update() of BIT for both insert and delete. To find rank, we simply call standard function sum() of BIT. To find k-th smallest element, we do binary search in BIT.
2nd Smallest element is 30 Rank of 40 is 3 Rank of 50 is 3
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
- Two Dimensional Binary Indexed Tree or Fenwick Tree
- Binary Indexed Tree or Fenwick Tree
- Number of elements greater than K in the range L to R using Fenwick Tree (Offline queries)
- Merge Sort Tree for Range Order Statistics
- Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
- Tournament Tree (Winner Tree) and Binary Heap
- Interval Tree
- B-Tree | Set 3 (Delete)
- B-Tree | Set 1 (Introduction)
- B-Tree | Set 2 (Insert)
- Quad Tree
- Cartesian Tree
- AVL Tree | Set 1 (Insertion)
- AVL Tree | Set 2 (Deletion)
- Reconstructing Segment Tree
Improved By : kapillamba4