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 email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
- Binary Indexed Tree or Fenwick Tree
- Two Dimensional Binary Indexed Tree or Fenwick Tree
- Number of elements greater than K in the range L to R using Fenwick Tree (Offline queries)
- XOR of elements in a given range with updates using Fenwick Tree
- Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
- Querying the number of distinct colors in a subtree of a colored tree using BIT
- Count inversions in an array | Set 3 (Using BIT)
- Counting Triangles in a Rectangular space using BIT
- Longest Increasing Subsequence using BIT
- Merge Sort Tree for Range Order Statistics
- k smallest elements in same order using O(1) extra space
- Print Strings In Reverse Dictionary Order Using Trie
- Find pair of rows in a binary matrix that has maximum bit difference
- Position of rightmost different bit
- Index of kth set bit in a binary array with update queries
- Queries for number of array elements in a range with Kth Bit Set
- Sort the array of strings according to alphabetical order defined by another string
- Find k-th smallest element in BST (Order Statistics in BST)
- Interval Tree using GNU Tree-based container
- Tournament Tree (Winner Tree) and Binary Heap