Find frequency of each element in a limited range array in less than O(n) time
Last Updated :
23 Jul, 2025
Given a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant M
Note: Do this without traversing the complete array. i.e. expected time complexity is less than O(n)
Examples:
Input: arr[] = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10]
Output:
Element 1 occurs 3 times
Element 2 occurs 1 times
Element 3 occurs 2 times
Element 5 occurs 2 times
Element 8 occurs 3 times
Element 9 occurs 2 times
Element 10 occurs 1 times
Input: arr[] = [2, 2, 6, 6, 7, 7, 7, 11]
Output:
Element 2 occurs 2 times
Element 6 occurs 2 times
Element 7 occurs 3 times
Element 11 occurs 1 times
[Naive Approach - 1] Using Linear Search - O(n) time and O(1) space
To solve the problem follow the below idea:
Traverse the input array and increment the frequency of the element if the current element and the previous element are the same, otherwise reset the frequency and print the element and its frequency
Follow the given steps to solve the problem:
- Initialize frequency to 1 and index to 1.
- Traverse the array from the index position and check if the current element is equal to the previous element.
- If yes, increment the frequency and index and repeat step 2. Otherwise, print the element and its frequency and repeat step 2.
- At last(corner case), print the last element and its frequency.
C++
// C++ program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
#include <bits/stdc++.h>
using namespace std;
void findFrequencies(vector<int> &arr) {
int n = arr.size();
int freq = 1;
int idx = 1;
int value = arr[0];
while (idx < n) {
// check if the current value is equal to
// previous value.
if (arr[idx - 1] == arr[idx]) {
freq++;
idx++;
}
else {
cout << value << " " << freq << endl;
value = arr[idx];
idx++;
// reset the frequency
freq = 1;
}
}
// print the last value and its frequency
cout << value << " " << freq;
}
int main() {
vector<int> arr
= {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10};
findFrequencies(arr);
return 0;
}
Java
// Java program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
class GfG {
static void findFrequencies(int[] arr) {
int n = arr.length;
int freq = 1;
int idx = 1;
int value = arr[0];
while (idx < n) {
// check if the current value is equal to
// previous value.
if (arr[idx - 1] == arr[idx]) {
freq++;
idx++;
}
else {
System.out.println(value + " " + freq);
value = arr[idx];
idx++;
// reset the frequency
freq = 1;
}
}
// print the last value and its frequency
System.out.println(value + " " + freq);
}
public static void main(String[] args) {
int[] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10};
findFrequencies(arr);
}
}
Python
# Python program to count number of occurrences of
# each value in the array in O(n) time and O(1) space
def findFrequencies(arr):
n = len(arr)
freq = 1
idx = 1
value = arr[0]
while idx < n:
# check if the current value is equal to
# previous value.
if arr[idx - 1] == arr[idx]:
freq += 1
idx += 1
else:
print(value, freq)
value = arr[idx]
idx += 1
# reset the frequency
freq = 1
# print the last value and its frequency
print(value, freq)
if __name__ == "__main__":
arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10]
findFrequencies(arr)
C#
// C# program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
using System;
class GfG {
static void findFrequencies(int[] arr) {
int n = arr.Length;
int freq = 1;
int idx = 1;
int value = arr[0];
while (idx < n) {
// check if the current value is equal to
// previous value.
if (arr[idx - 1] == arr[idx]) {
freq++;
idx++;
}
else {
Console.WriteLine(value + " " + freq);
value = arr[idx];
idx++;
// reset the frequency
freq = 1;
}
}
// print the last value and its frequency
Console.WriteLine(value + " " + freq);
}
static void Main() {
int[] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10};
findFrequencies(arr);
}
}
JavaScript
// JavaScript program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
function findFrequencies(arr) {
let n = arr.length;
let freq = 1;
let idx = 1;
let value = arr[0];
while (idx < n) {
// check if the current value is equal to
// previous value.
if (arr[idx - 1] === arr[idx]) {
freq++;
idx++;
}
else {
console.log(value + " " + freq);
value = arr[idx];
idx++;
// reset the frequency
freq = 1;
}
}
// print the last value and its frequency
console.log(value + " " + freq);
}
let arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10];
findFrequencies(arr);
Output1 3
2 1
3 2
5 2
8 3
9 2
10 1
[Expected Approach] Using Binary Search - O(m log(n)) time and O(1) space
The idea is to leverage the sorted nature of the array by using binary search to find the last occurrence of each unique element.
- Starting from the first element, we keep track of its value and use binary search to find the rightmost index where this value appears.
- This gives us the frequency by calculating the difference between the starting and ending indices.
- After finding the frequency of one element, we jump to the next unique element by moving our pointer beyond the last occurrence we found.
Step by step approach:
- Start with index i = 0 and get the current value val = arr[i]
- Use binary search to find the last occurrence (endIndex) of val in the array
- Calculate frequency as (endIndex - i + 1)
- Print the value and its frequency
- Update i to (endIndex + 1) to skip to the next unique element
- Repeat until we reach the end of the array
C++
// C++ program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
#include <bits/stdc++.h>
using namespace std;
// It print number of
// occurrences of each element in the array.
void findFrequencies(vector<int> &arr) {
int n = arr.size();
int i = 0;
while (i<n) {
int val = arr[i];
int s = i, e = n-1;
int endIndex = i;
while (s<=e) {
int mid = s + (e-s)/2;
if (arr[mid] == val) {
endIndex = mid;
s = mid + 1;
}
else {
e = mid - 1;
}
}
int cnt = endIndex - i + 1;
cout << val << " " << cnt << endl;
// Set i to next value index
i = endIndex + 1;
}
}
int main() {
vector<int> arr
= {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10};
findFrequencies(arr);
return 0;
}
Java
// Java program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
class GfG {
// It prints number of
// occurrences of each element in the array.
static void findFrequencies(int[] arr) {
int n = arr.length;
int i = 0;
while (i < n) {
int val = arr[i];
int s = i, e = n - 1;
int endIndex = i;
while (s <= e) {
int mid = s + (e - s) / 2;
if (arr[mid] == val) {
endIndex = mid;
s = mid + 1;
}
else {
e = mid - 1;
}
}
int cnt = endIndex - i + 1;
System.out.println(val + " " + cnt);
// Set i to next value index
i = endIndex + 1;
}
}
public static void main(String[] args) {
int[] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10};
findFrequencies(arr);
}
}
Python
# Python program to count number of occurrences of
# each value in the array in O(n) time and O(1) space
# It prints number of
# occurrences of each element in the array.
def findFrequencies(arr):
n = len(arr)
i = 0
while i < n:
val = arr[i]
s, e = i, n - 1
endIndex = i
while s <= e:
mid = s + (e - s) // 2
if arr[mid] == val:
endIndex = mid
s = mid + 1
else:
e = mid - 1
cnt = endIndex - i + 1
print(val, cnt)
# Set i to next value index
i = endIndex + 1
if __name__ == "__main__":
arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10]
findFrequencies(arr)
C#
// C# program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
using System;
class GfG {
// It prints number of
// occurrences of each element in the array.
static void findFrequencies(int[] arr) {
int n = arr.Length;
int i = 0;
while (i < n) {
int val = arr[i];
int s = i, e = n - 1;
int endIndex = i;
while (s <= e) {
int mid = s + (e - s) / 2;
if (arr[mid] == val) {
endIndex = mid;
s = mid + 1;
}
else {
e = mid - 1;
}
}
int cnt = endIndex - i + 1;
Console.WriteLine(val + " " + cnt);
// Set i to next value index
i = endIndex + 1;
}
}
static void Main() {
int[] arr = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10};
findFrequencies(arr);
}
}
JavaScript
// JavaScript program to count number of occurrences of
// each value in the array in O(n) time and O(1) space
// It prints number of
// occurrences of each element in the array.
function findFrequencies(arr) {
let n = arr.length;
let i = 0;
while (i < n) {
let val = arr[i];
let s = i, e = n - 1;
let endIndex = i;
while (s <= e) {
let mid = Math.floor(s + (e - s) / 2);
if (arr[mid] === val) {
endIndex = mid;
s = mid + 1;
}
else {
e = mid - 1;
}
}
let cnt = endIndex - i + 1;
console.log(val + " " + cnt);
// Set i to next value index
i = endIndex + 1;
}
}
let arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10];
findFrequencies(arr);
Output1 3
2 1
3 2
5 2
8 3
9 2
10 1
Time Complexity: O(m log n). Where m is the number of distinct elements in the array of size n. Since m <= M (a constant) (elements are in a limited range), the time complexity of this solution is O(log N)
Auxiliary Space: O(1)
Frequency of Limited Range Array Elements in Data Structures and Algorithms (DSA) | Programming Tutorial
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem