Table of contents
1.
Introduction 
1.1.
Problem Statement 
1.2.
Sample Examples 
2.
Linear Traversal Approach 
2.1.
Algorithm 
2.2.
Implementation in C++
2.2.1.
Time Complexity 
2.2.2.
Space Complexity 
3.
Sorting and Binary Search Approach 
3.1.
Algorithm 
3.2.
Implementation in C++
3.2.1.
Time Complexity 
3.2.2.
Space Complexity 
4.
Frequently Asked Questions 
4.1.
What is a rank in a BST?
4.2.
How do you find the rank of an element?
4.3.
What is meant by the rank of a matrix?
5.
Conclusion 
Last Updated: Mar 27, 2024
Easy

Rank of an Element in a Stream

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

The rank of an element in-stream is the “Total number of elements which are equal to or less than x (not including x)”. A typical array search question is to find an element's rank in a stream. It is only easy when you know the right gest to the question. Otherwise, if you read the problem statement without knowing its meaning, you’ll find it a tricky question.

Rank of an element in a stream

This article will discuss the problem of finding the rank of an element in a stream. We will use two approaches to find the solution to the given problem. The first is by linear traversal of the array. And then, by sorting and doing a binary search of the array.

Let’s see the problem statement of this question.

Problem Statement 

We are given a key and a stream of elements. We need to find the rank of key value in that stream.

problem statement

Sample Examples 

Example 1:

Input:  

arr[] = {15, 25, 20, 8, 9, 7, 1}, x = 9;
example1

Output

Rank of 9 in the stream is: 3

 

Explanation: Three elements are less than or equal to 9 (and not including 9).

 

Example 2:

Input

arr[] = {8, 3, 17, 7, 18, 12, 10, 25, 13}, x = 25;
example2

Output

Rank of 25 in the stream is: 8

 

Explanation: Eight elements are less than or equal to 25 (and not including 25).

Linear Traversal Approach 

In this approach, find the rank of an element in a stream. We are comparing the key value element with all the array elements. Let’s see the algorithm of this approach.

Algorithm 

  1. We will start from the leftmost element of the array. And one by one, compare the key value x with each array element.
  2. If x is greater than the element, increase the value of count by 1.
  3. If x doesn’t match with any of the elements, return -1.

Implementation in C++

#include <bits/stdc++.h>
using namespace std;

#define FAST ios_base::sync_with_stdio(false); cin.tie(NULL);

//------------------Main Function------------------//
int main()
	{
	    FAST;
		int array[] = {8, 3, 17, 7, 18, 12, 10, 25, 13};
		int key_value = 25;
		int arraySize = sizeof(array)/sizeof(array[0]);
		int count = 0;
		for(int i = 0; i < arraySize; i++)
			{
				if(array[i] <= key_value)
				{
					count += 1;
				}
			}
		cout << "Rank of the " << key_value << " in stream is: " << count-1 << endl;
		return 0;
	}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

output

Time Complexity 

The time complexity of the above-used approach is O(n), where n is the array's length. It is because we are comparing key values of all the components.

Space Complexity 

The space complexity of the above-used approach is O(1), as no extra space is used.

Sorting and Binary Search Approach 

A more straightforward way to implement this operation is to use an array. It will hold all the elements in sorted order. And when a new element is inserted, we would shift the elements. And then, we perform a binary search on the array to get the right-most element of x and return that element. The function to find rank would work in O(log n) time. But insertion operation would be costly.

Algorithm 

  1. We will use an array that will hold all the elements in sorted order. 
  2. Now when a new element is inserted, we would shift the elements.
  3. Now, we traverse the tree from the root node and compare the root values to x. We will get the following cases. 
    1. When root->data == x, then return size of left subtree of root.
    2. If x < root->data, then return getRank(root->left)
    3. And if x > root->data, then return getRank(root->right) + size of left subtree + 1.

Implementation in C++

#include <bits/stdc++.h>
using namespace std;

#define FAST ios_base::sync_with_stdio(false); cin.tie(NULL);

class Node
	{
	    public:
		int data;
		Node *left, *right;
		int leftSize;
	};

//----------------------Utility Function To Create New Node----------------------//
Node* newNode(int data)
	{
		Node *temp = new Node;
		temp->data = data;
		temp->left = temp->right = NULL;
		temp->leftSize = 0;
		return temp;
	}

//----------------------Utility Function To Insert Node----------------------//
Node* insertfxn(Node*& root, int data)
	{
		if (!root)
		return newNode(data);

	// Now updating the size of left subtree.
		if (data <= root->data) 
			{
				root->left = insertfxn(root->left, data);
				root->leftSize++;
			}
		else
			root->right = insertfxn(root->right, data);

		return root;
	}

//----------------------Utility Function To find rank of Node----------------------//
int findRank(Node* root, int x)
	{
	// When root->data == x, return size of left subtree of root.
		if (root->data == x)
		return root->leftSize;

	//If x < root->data, return findRank(root->left)
		if (x < root->data) 
		{
			if (!root->left)
				return -1;
			else
				return findRank(root->left, x);
		}

	//If x > root->data, return findRank(root->right) + size of left subtree + 1.
		else 
		{
				if (!root->right)
					return -1;
				else 
				{
					int rightSize = findRank(root->right, x);
					if(rightSize == -1 ) return -1;
					return root->leftSize + 1 + rightSize;
				}
		}
	}

//------------------Main Function------------------//
int main()
{
	    FAST;
		int arr[] = {8, 3, 17, 7, 18, 12, 10, 25, 13};
		int n = sizeof(arr) / sizeof(arr[0]);
		int x = 25;

		Node* root = NULL;
		for (int i = 0; i < n; i++)
		root = insertfxn(root, arr[i]);
	
	cout << "Rank of the " << x << " in stream is: "<< findRank(root, x) << endl;
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

output

Time Complexity 

The time complexity of the above-used approach is O(n), where n is the array's length. It is because of the insertion operation we are using.

Space Complexity 

The space complexity of the above-used approach is O(1), as no extra space is used.

Check out this array problem - Merge 2 Sorted Arrays

Frequently Asked Questions 

What is a rank in a BST?

The rank of a node in a tree is the number of nodes whose values are less than or equal to x. The nodes can be of any data type as long as they have an ordering relation.

How do you find the rank of an element?

The rank of an element in-stream is the “Total number of elements which are equal to or less than x (not including x)”.  Here, if an element is not found in the stream or is the smallest in the stream, we will return -1.

What is meant by the rank of a matrix?

The rank of a matrix is the highest number of its linearly independent row vectors (or column vectors). From here, it is obvious that the rank of a matrix cannot surpass the number of its rows (or columns).

Conclusion 

This article briefly discussed the problem of finding the rank of an element in a stream.

We hope that this blog has helped you enhance your knowledge about the problem to find the rank of an element and if you would like to learn more, check out our articles Multistage GraphPrint BST keys in the given valid rangeMinimize the number of weakly connected nodesCount BST subtrees that lie in a given rangeConvert BST to the Greatest Sum Tree, and Replace each node in a binary tree with a sum of its in order predecessor and successor. You can also refer to our guided path on the basics of java and many more on our Website.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, and many more! If you wish to test your competency in coding, you may check out the mock test series. You can also participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Happy learning!

Live masterclass