Count frequencies of all elements in array in O(1) extra space and O(n) time
Last Updated :
10 May, 2024
Given an unsorted array of n integers that can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count the frequency of all elements that are present and print the missing elements.
Examples:
Input: arr[] = {2, 3, 3, 2, 5}
Output: Below are frequencies of all elements
1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
Explanation: Frequency of elements 1 is 0, 2 is 2, 3 is 2, 4 is 0 and 5 is 1.
Input: arr[] = {4, 4, 4, 4}
Output: Below are frequencies of all elements
1 -> 0
2 -> 0
3 -> 0
4 -> 4
Explanation: Frequency of elements 1 is 0, 2 is 0, 3 is 0 and 4 is 4.
Naive Solution:
Create an extra space of size n, as elements of the array is in the range 1 to n. Use the extra space as HashMap. Traverse the array and update the count of the current element. Finally, print the frequencies of the HashMap along with the indices.
Step-by-step approach:
- Create an extra space of size n (hm), use it as a HashMap.
- Traverse the array from start to end.
- For every element update hm[array[i]-1], i.e. hm[array[i]-1]++
- Run a loop from 0 to n and print hm[array[i]-1] along with the index i
Below is the implementation of the above approach:
C++
// C++ program to print frequencies of all array
// elements in O(n) extra space and O(n) time
#include<bits/stdc++.h>
using namespace std;
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void findCounts(int *arr, int n)
{
//Hashmap
int hash[n]={0};
// Traverse all array elements
int i = 0;
while (i<n)
{
//update the frequency of array[i]
hash[arr[i]-1]++;
//increase the index
i++;
}
printf("\nBelow are counts of all elements\n");
for (int i=0; i<n; i++)
printf("%d -> %d\n", i+1, hash[i]);
}
// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 2, 5};
findCounts(arr, sizeof(arr)/ sizeof(arr[0]));
int arr1[] = {1};
findCounts(arr1, sizeof(arr1)/ sizeof(arr1[0]));
int arr3[] = {4, 4, 4, 4};
findCounts(arr3, sizeof(arr3)/ sizeof(arr3[0]));
int arr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1};
findCounts(arr2, sizeof(arr2)/ sizeof(arr2[0]));
int arr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3};
findCounts(arr4, sizeof(arr4)/ sizeof(arr4[0]));
int arr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
findCounts(arr5, sizeof(arr5)/ sizeof(arr5[0]));
int arr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
findCounts(arr6, sizeof(arr6)/ sizeof(arr6[0]));
return 0;
}
Java
// Java program to print frequencies of all array
// elements in O(n) extra space and O(n) time
import java.util.*;
class GFG{
// Function to find counts of all elements
// present in arr[0..n-1]. The array elements
// must be range from 1 to n
public static void findCounts(int arr[], int n)
{
// Hashmap
int hash[] = new int[n];
Arrays.fill(hash, 0);
// Traverse all array elements
int i = 0;
while (i < n)
{
// Update the frequency of array[i]
hash[arr[i] - 1]++;
// Increase the index
i++;
}
System.out.println("\nBelow are counts " +
"of all elements");
for(i = 0; i < n; i++)
{
System.out.println((i + 1) + " -> " +
hash[i]);
}
}
// Driver code
public static void main(String []args)
{
int arr[] = { 2, 3, 3, 2, 5 };
findCounts(arr, arr.length);
int arr1[] = {1};
findCounts(arr1, arr1.length);
int arr3[] = { 4, 4, 4, 4 };
findCounts(arr3, arr3.length);
int arr2[] = { 1, 3, 5, 7, 9,
1, 3, 5, 7, 9, 1 };
findCounts(arr2, arr2.length);
int arr4[] = { 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3 };
findCounts(arr4, arr4.length);
int arr5[] = { 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11 };
findCounts(arr5, arr5.length);
int arr6[] = { 11, 10, 9, 8, 7,
6, 5, 4, 3, 2, 1 };
findCounts(arr6, arr6.length);
}
}
// This code is contributed by rag2127
Python
# Python3 program to print frequencies
# of all array elements in O(n) extra
# space and O(n) time
# Function to find counts of all
# elements present in arr[0..n-1].
# The array elements must be range
# from 1 to n
def findCounts(arr, n):
# Hashmap
hash = [0 for i in range(n)]
# Traverse all array elements
i = 0
while (i < n):
# Update the frequency of array[i]
hash[arr[i] - 1] += 1
# Increase the index
i += 1
print("Below are counts of all elements")
for i in range(n):
print(i + 1, "->", hash[i], end = " ")
print()
# Driver code
arr = [ 2, 3, 3, 2, 5 ]
findCounts(arr, len(arr))
arr1 = [1]
findCounts(arr1, len(arr1))
arr3 = [ 4, 4, 4, 4 ]
findCounts(arr3, len(arr3))
arr2 = [ 1, 3, 5, 7, 9,
1, 3, 5, 7, 9, 1 ]
findCounts(arr2, len(arr2))
arr4 = [ 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3 ]
findCounts(arr4, len(arr4))
arr5 = [ 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11 ]
findCounts(arr5, len(arr5))
arr6 = [ 11, 10, 9, 8, 7,
6, 5, 4, 3, 2, 1 ]
findCounts(arr6, len(arr6))
# This code is contributed by avanitrachhadiya2155
C#
// C# program to print frequencies of all array
// elements in O(n) extra space and O(n) time
using System;
class GFG
{
// Function to find counts of all elements
// present in arr[0..n-1]. The array elements
// must be range from 1 to n
public static void findCounts(int[] arr, int n)
{
// Hashmap
int[] hash = new int[n];
// Traverse all array elements
int i = 0;
while (i < n)
{
// Update the frequency of array[i]
hash[arr[i] - 1]++;
// Increase the index
i++;
}
Console.WriteLine("\nBelow are counts "
+ "of all elements");
for (i = 0; i < n; i++)
{
Console.WriteLine((i + 1) + " -> " + hash[i]);
}
}
// Driver code
static public void Main()
{
int[] arr = new int[] { 2, 3, 3, 2, 5 };
findCounts(arr, arr.Length);
int[] arr1 = new int[] { 1 };
findCounts(arr1, arr1.Length);
int[] arr3 = new int[] { 4, 4, 4, 4 };
findCounts(arr3, arr3.Length);
int[] arr2
= new int[] { 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1 };
findCounts(arr2, arr2.Length);
int[] arr4
= new int[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
findCounts(arr4, arr4.Length);
int[] arr5 = new int[] { 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11 };
findCounts(arr5, arr5.Length);
int[] arr6 = new int[] { 11, 10, 9, 8, 7, 6,
5, 4, 3, 2, 1 };
findCounts(arr6, arr6.Length);
}
}
// This code is contributed by Dharanendra L V
JavaScript
<script>
// Javascript program to print frequencies of all array
// elements in O(n) extra space and O(n) time
// Function to find counts of all elements
// present in arr[0..n-1]. The array elements
// must be range from 1 to n
function findCounts(arr,n)
{
// Hashmap
let hash = new Array(n);
for(let i=0;i<n;i++)
{
hash[i]=0;
}
// Traverse all array elements
let i = 0;
while (i < n)
{
// Update the frequency of array[i]
hash[arr[i] - 1]++;
// Increase the index
i++;
}
document.write("<br>Below are counts " +
"of all elements<br>");
for(i = 0; i < n; i++)
{
document.write((i + 1) + " -> " +
hash[i]+"<br>");
}
}
// Driver code
let arr = [ 2, 3, 3, 2, 5 ];
findCounts(arr, arr.length);
let arr1 = [1];
findCounts(arr1, arr1.length);
let arr3 = [ 4, 4, 4, 4 ];
findCounts(arr3, arr3.length);
let arr2 = [ 1, 3, 5, 7, 9,
1, 3, 5, 7, 9, 1 ];
findCounts(arr2, arr2.length);
let arr4 = [ 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3 ];
findCounts(arr4, arr4.length);
let arr5 = [ 1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11 ];
findCounts(arr5, arr5.length);
let arr6 = [ 11, 10, 9, 8, 7,
6, 5, 4, 3, 2, 1 ];
findCounts(arr6, arr6.length);
// This code is contributed by ab2127
</script>
OutputBelow are counts of all elements
1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
Below are counts of all elements
1 -> 1
Below are counts of all elements
1 -> 0
2 -> 0
3 -> 0
4 -> 4
Below are counts of all elements
1 -> 3
2 -> 0
3 -> 2
4 -> 0
5 -> 2
6 -> 0
7 -> 2
8 -> 0
9 -> 2
10 -> 0
11 -> 0
Below are counts of all elements
1 -> 0
2 -> 0
3 -> 11
4 -> 0
5 -> 0
6 -> 0
7 -> 0
8 -> 0
9 -> 0
10 -> 0
11 -> 0
Below are counts of all elements
1 -> 1
2 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
7 -> 1
8 -> 1
9 -> 1
10 -> 1
11 -> 1
Below are counts of all elements
1 -> 1
2 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
7 -> 1
8 -> 1
9 -> 1
10 -> 1
11 -> 1
Time Complexity: O(n). As a single traversal of array takes O(n) time.
Auxiliary Space Complexity: O(n). To store all the elements in a HashMap O(n) space is needed.
Efficient Approach: By making elements negative.
The idea is to traverse the given array, use elements as an index and store their counts at the index. Consider the basic approach, a Hashmap of size n is needed and the array is also of size n. So the array can be used as a hashmap, all the elements of the array are from 1 to n, i.e. all are positive elements. So the frequency can be stored as negative. This might lead to a problem. Let i-th element be a then the count should be stored at array[a-1], but when the frequency will be stored the element will be lost. To deal with this problem, first, replace the ith element by array[a-1] and then put -1 at array[a-1]. So our idea is to replace the element by frequency and store the element in the current index and if the element at array[a-1] is already negative, then it is already replaced by a frequency so decrement array[a-1].
Step-by-step approach:
- Traverse the array from start to end.
- For each element check if the element is less than or equal to zero or not. If negative or zero skip the element as it is frequency.
- If an element (e = array[i] – 1 ) is positive, then check if array[e] is positive or not.
- If positive then that means it is the first occurrence of e in the array and replace array[i] with array[e], i.earray[i] = array[e] and assign array[e] = -1.
- If array[e] is negative, then it is not the first occurrence, the update array[e] as array[e]– and update array[i] as array[i] = 0.
- Again, traverse the array and print i+1 as value and array[i] as frequency.
Below is the implementation of the above approach:
C++
// C++ program to print frequencies of all array
// elements in O(1) extra space and O(n) time
#include<bits/stdc++.h>
using namespace std;
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void findCounts(int *arr, int n)
{
// Traverse all array elements
int i = 0;
while (i<n)
{
// If this element is already processed,
// then nothing to do
if (arr[i] <= 0)
{
i++;
continue;
}
// Find index corresponding to this element
// For example, index for 5 is 4
int elementIndex = arr[i]-1;
// If the elementIndex has an element that is not
// processed yet, then first store that element
// to arr[i] so that we don't lose anything.
if (arr[elementIndex] > 0)
{
arr[i] = arr[elementIndex];
// After storing arr[elementIndex], change it
// to store initial count of 'arr[i]'
arr[elementIndex] = -1;
}
else
{
// If this is NOT first occurrence of arr[i],
// then decrement its count.
arr[elementIndex]--;
// And initialize arr[i] as 0 means the element
// 'i+1' is not seen so far
arr[i] = 0;
i++;
}
}
printf("\nBelow are counts of all elements\n");
for (int i=0; i<n; i++)
printf("%d -> %d\n", i+1, abs(arr[i]));
}
// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 2, 5};
findCounts(arr, sizeof(arr)/ sizeof(arr[0]));
int arr1[] = {1};
findCounts(arr1, sizeof(arr1)/ sizeof(arr1[0]));
int arr3[] = {4, 4, 4, 4};
findCounts(arr3, sizeof(arr3)/ sizeof(arr3[0]));
int arr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1};
findCounts(arr2, sizeof(arr2)/ sizeof(arr2[0]));
int arr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3};
findCounts(arr4, sizeof(arr4)/ sizeof(arr4[0]));
int arr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
findCounts(arr5, sizeof(arr5)/ sizeof(arr5[0]));
int arr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
findCounts(arr6, sizeof(arr6)/ sizeof(arr6[0]));
return 0;
}
Java
// Java program to print frequencies of all array
// elements in O(1) extra space and O(n) time
class CountFrequencies
{
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void findCounts(int arr[], int n)
{
// Traverse all array elements
int i = 0;
while (i < n)
{
// If this element is already processed,
// then nothing to do
if (arr[i] <= 0)
{
i++;
continue;
}
// Find index corresponding to this element
// For example, index for 5 is 4
int elementIndex = arr[i] - 1;
// If the elementIndex has an element that is not
// processed yet, then first store that element
// to arr[i] so that we don't lose anything.
if (arr[elementIndex] > 0)
{
arr[i] = arr[elementIndex];
// After storing arr[elementIndex], change it
// to store initial count of 'arr[i]'
arr[elementIndex] = -1;
}
else
{
// If this is NOT first occurrence of arr[i],
// then decrement its count.
arr[elementIndex]--;
// And initialize arr[i] as 0 means the element
// 'i+1' is not seen so far
arr[i] = 0;
i++;
}
}
System.out.println("Below are counts of all elements");
for (int j = 0; j < n; j++)
System.out.println(j+1 + "->" + Math.abs(arr[j]));
}
// Driver program to test above functions
public static void main(String[] args)
{
CountFrequencies count = new CountFrequencies();
int arr[] = {2, 3, 3, 2, 5};
count.findCounts(arr, arr.length);
int arr1[] = {1};
count.findCounts(arr1, arr1.length);
int arr3[] = {4, 4, 4, 4};
count.findCounts(arr3, arr3.length);
int arr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1};
count.findCounts(arr2, arr2.length);
int arr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3};
count.findCounts(arr4, arr4.length);
int arr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
count.findCounts(arr5, arr5.length);
int arr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
count.findCounts(arr6, arr6.length);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
# Python3 program to print frequencies of all array
# elements in O(1) extra space and O(n) time
# Function to find counts of all elements present in
# arr[0..n-1]. The array elements must be range from
# 1 to n
def findCounts(arr, n):
# Traverse all array elements
i = 0
while i<n:
# If this element is already processed,
# then nothing to do
if arr[i] <= 0:
i += 1
continue
# Find index corresponding to this element
# For example, index for 5 is 4
elementIndex = arr[i] - 1
# If the elementIndex has an element that is not
# processed yet, then first store that element
# to arr[i] so that we don't lose anything.
if arr[elementIndex] > 0:
arr[i] = arr[elementIndex]
# After storing arr[elementIndex], change it
# to store initial count of 'arr[i]'
arr[elementIndex] = -1
else:
# If this is NOT first occurrence of arr[i],
# then decrement its count.
arr[elementIndex] -= 1
# And initialize arr[i] as 0 means the element
# 'i+1' is not seen so far
arr[i] = 0
i += 1
print ("Below are counts of all elements")
for i in range(0,n):
print ("%d -> %d"%(i+1, abs(arr[i])))
print ("")
# Driver program to test above function
arr = [2, 3, 3, 2, 5]
findCounts(arr, len(arr))
arr1 = [1]
findCounts(arr1, len(arr1))
arr3 = [4, 4, 4, 4]
findCounts(arr3, len(arr3))
arr2 = [1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1]
findCounts(arr2, len(arr2))
arr4 = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
findCounts(arr4, len(arr4))
arr5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
findCounts(arr5, len(arr5))
arr6 = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
findCounts(arr6, len(arr6))
# This code is contributed
# by shreyanshi_19
C#
// C# program to print frequencies of
// all array elements in O(1) extra
// space and O(n) time
using System;
class GFG
{
// Function to find counts of all
// elements present in arr[0..n-1].
// The array elements must be range
// from 1 to n
void findCounts(int[] arr, int n)
{
// Traverse all array elements
int i = 0;
while (i < n)
{
// If this element is already
// processed, then nothing to do
if (arr[i] <= 0)
{
i++;
continue;
}
// Find index corresponding to
// this element. For example,
// index for 5 is 4
int elementIndex = arr[i] - 1;
// If the elementIndex has an element
// that is not processed yet, then
// first store that element to arr[i]
// so that we don't loose anything.
if (arr[elementIndex] > 0)
{
arr[i] = arr[elementIndex];
// After storing arr[elementIndex],
// change it to store initial count
// of 'arr[i]'
arr[elementIndex] = -1;
}
else
{
// If this is NOT first occurrence
// of arr[i], then decrement its count.
arr[elementIndex]--;
// And initialize arr[i] as 0 means
// the element 'i+1' is not seen so far
arr[i] = 0;
i++;
}
}
Console.Write("\nBelow are counts of " +
"all elements" + "\n");
for (int j = 0; j < n; j++)
Console.Write(j + 1 + "->" +
Math.Abs(arr[j]) + "\n");
}
// Driver Code
public static void Main()
{
GFG count = new GFG();
int[] arr = {2, 3, 3, 2, 5};
count.findCounts(arr, arr.Length);
int[] arr1 = {1};
count.findCounts(arr1, arr1.Length);
int[] arr3 = {4, 4, 4, 4};
count.findCounts(arr3, arr3.Length);
int[] arr2 = {1, 3, 5, 7, 9, 1,
3, 5, 7, 9, 1};
count.findCounts(arr2, arr2.Length);
int[] arr4 = {3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3};
count.findCounts(arr4, arr4.Length);
int[] arr5 = {1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11};
count.findCounts(arr5, arr5.Length);
int[] arr6 = {11, 10, 9, 8, 7, 6,
5, 4, 3, 2, 1};
count.findCounts(arr6, arr6.Length);
}
}
// This code is contributed by ChitraNayal
JavaScript
<script>
// Javascript program to print frequencies
// of all array elements in O(1) extra
// space and O(n) time
// Function to find counts of all elements
// present in arr[0..n-1]. The array
// elements must be range from 1 to n
function findCounts(arr, n)
{
// Traverse all array elements
let i = 0;
while (i < n)
{
// If this element is already processed,
// then nothing to do
if (arr[i] <= 0)
{
i++;
continue;
}
// Find index corresponding to this element
// For example, index for 5 is 4
let elementIndex = arr[i] - 1;
// If the elementIndex has an element that
// is not processed yet, then first store
// that element to arr[i] so that we don't
// lose anything.
if (arr[elementIndex] > 0)
{
arr[i] = arr[elementIndex];
// After storing arr[elementIndex],
// change it to store initial count
// of 'arr[i]'
arr[elementIndex] = -1;
}
else
{
// If this is NOT first occurrence
// of arr[i], then decrement its count.
arr[elementIndex]--;
// And initialize arr[i] as 0 means
// the element 'i+1' is not seen so far
arr[i] = 0;
i++;
}
}
document.write("<br>Below are counts of all elements<br>");
for(let j = 0; j < n; j++)
document.write(j+1 + "->" +
Math.abs(arr[j]) + "<br>");
}
// Driver code
let arr = [ 2, 3, 3, 2, 5 ];
findCounts(arr, arr.length);
let arr1 = [ 1 ];
findCounts(arr1, arr1.length);
let arr3 = [ 4, 4, 4, 4 ];
findCounts(arr3, arr3.length);
let arr2 = [ 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1 ];
findCounts(arr2, arr2.length);
let arr4 = [ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ];
findCounts(arr4, arr4.length);
let arr5 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ];
findCounts(arr5, arr5.length);
let arr6 = [ 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ];
findCounts(arr6, arr6.length);
// This code is contributed by unknown2108
</script>
OutputBelow are counts of all elements
1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
Below are counts of all elements
1 -> 1
Below are counts of all elements
1 -> 0
2 -> 0
3 -> 0
4 -> 4
Below are counts of all elements
1 -> 3
2 -> 0
3 -> 2
4 -> 0
5 -> 2
6 -> 0
7 -> 2
8 -> 0
9 -> 2
10 -> 0
11 -> 0
Below are counts of all elements
1 -> 0
2 -> 0
3 -> 11
4 -> 0
5 -> 0
6 -> 0
7 -> 0
8 -> 0
9 -> 0
10 -> 0
11 -> 0
Below are counts of all elements
1 -> 1
2 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
7 -> 1
8 -> 1
9 -> 1
10 -> 1
11 -> 1
Below are counts of all elements
1 -> 1
2 -> 1
3 -> 1
4 -> 1
5 -> 1
6 -> 1
7 -> 1
8 -> 1
9 -> 1
10 -> 1
11 -> 1
Time Complexity: O(n). As a single traversal of the array takes O(n) time.
Auxiliary Space: O(1). Since no extra space is needed.
Efficient Approach: By adding ‘n’ to keep track of counts.
All the array elements are from 1 to n. Reduce every element by 1. The array elements now are in range 0 to n-1 so it can be said that for every index i, floor(array[i]/n) = 0.
So as previously said that the idea is to traverse the given array, use elements as an index and store their counts at the index. Consider the basic approach, a Hashmap of size n is needed and the array is also of size n. So the array can be used as a hashmap but the difference is that instead of replacing elements add n to the array[i]th index.
So after updating the array[i]%n will give the ith element and array[i]/n will give the frequency of i+1.
Step-by-step approach:
- Traverse the array from start to end and reduce all the elements by 1.
- Again traverse the array from start to end.
- For each element array[i]%n update array[array[i]%n], i.e array[array[i]%n]+n
- Traverse the array from start to end and print i + 1 as value and array[i]/n as frequency.
Below is the implementation of the above approach:
C++
// C++ program to print frequencies of all array
// elements in O(1) extra space and O(n) time
#include<bits/stdc++.h>
using namespace std;
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void printfrequency(int arr[],int n)
{
// Subtract 1 from every element so that the elements
// become in range from 0 to n-1
for (int j =0; j<n; j++)
arr[j] = arr[j]-1;
// Use every element arr[i] as index and add 'n' to
// element present at arr[i]%n to keep track of count of
// occurrences of arr[i]
for (int i=0; i<n; i++)
arr[arr[i]%n] = arr[arr[i]%n] + n;
// To print counts, simply print the number of times n
// was added at index corresponding to every element
for (int i =0; i<n; i++)
cout << i + 1 << " -> " << arr[i]/n << endl;
}
// Driver program to test above function
int main()
{
int arr[] = {2, 3, 3, 2, 5};
int n = sizeof(arr)/sizeof(arr[0]);
printfrequency(arr,n);
return 0;
}
Java
class CountFrequency
{
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
void printfrequency(int arr[], int n)
{
// Subtract 1 from every element so that the elements
// become in range from 0 to n-1
for (int j = 0; j < n; j++)
arr[j] = arr[j] - 1;
// Use every element arr[i] as index and add 'n' to
// element present at arr[i]%n to keep track of count of
// occurrences of arr[i]
for (int i = 0; i < n; i++)
arr[arr[i] % n] = arr[arr[i] % n] + n;
// To print counts, simply print the number of times n
// was added at index corresponding to every element
for (int i = 0; i < n; i++)
System.out.println(i + 1 + "->" + arr[i] / n);
}
// Driver program to test above functions
public static void main(String[] args)
{
CountFrequency count = new CountFrequency();
int arr[] = {2, 3, 3, 2, 5};
int n = arr.length;
count.printfrequency(arr, n);
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Python 3 program to print frequencies
# of all array elements in O(1) extra
# space and O(n) time
# Function to find counts of all elements
# present in arr[0..n-1]. The array
# elements must be range from 1 to n
def printfrequency(arr, n):
# Subtract 1 from every element so that
# the elements become in range from 0 to n-1
for j in range(n):
arr[j] = arr[j] - 1
# Use every element arr[i] as index
# and add 'n' to element present at
# arr[i]%n to keep track of count of
# occurrences of arr[i]
for i in range(n):
arr[arr[i] % n] = arr[arr[i] % n] + n
# To print counts, simply print the
# number of times n was added at index
# corresponding to every element
for i in range(n):
print(i + 1, "->", arr[i] // n)
# Driver code
arr = [2, 3, 3, 2, 5]
n = len(arr)
printfrequency(arr, n)
# This code is contributed
# by Shrikant13
C#
using System;
internal class CountFrequency
{
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
internal virtual void printfrequency(int[] arr, int n)
{
// Subtract 1 from every element so that the elements
// become in range from 0 to n-1
for (int j = 0; j < n; j++)
{
arr[j] = arr[j] - 1;
}
// Use every element arr[i] as index and add 'n' to
// element present at arr[i]%n to keep track of count of
// occurrences of arr[i]
for (int i = 0; i < n; i++)
{
arr[arr[i] % n] = arr[arr[i] % n] + n;
}
// To print counts, simply print the number of times n
// was added at index corresponding to every element
for (int i = 0; i < n; i++)
{
Console.WriteLine(i + 1 + "->" + arr[i] / n);
}
}
// Driver program to test above functions
public static void Main(string[] args)
{
CountFrequency count = new CountFrequency();
int[] arr = new int[] {2, 3, 3, 2, 5};
int n = arr.Length;
count.printfrequency(arr, n);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
function printfrequency(arr, n)
{
// Subtract 1 from every element so that the elements
// become in range from 0 to n-1
for (let j = 0; j < n; j++)
arr[j] = arr[j] - 1;
// Use every element arr[i] as index and add 'n' to
// element present at arr[i]%n to keep track of count of
// occurrences of arr[i]
for (let i = 0; i < n; i++)
arr[arr[i] % n] = arr[arr[i] % n] + n;
// To print counts, simply print the number of times n
// was added at index corresponding to every element
for (let i = 0; i < n; i++)
document.write((i + 1) + " -> " + parseInt(arr[i] / n, 10) + "</br>");
}
let arr = [2, 3, 3, 2, 5];
let n = arr.length;
printfrequency(arr, n);
// This code is contributed by divyeshrabadiya07.
</script>
PHP
<?php
// PHP program to print
// frequencies of all
// array elements in O(1)
// extra space and O(n) time
// Function to find counts
// of all elements present
// in arr[0..n-1]. The array
// elements must be range
// from 1 to n
function printfrequency($arr,$n)
{
// Subtract 1 from every
// element so that the
// elements become in
// range from 0 to n-1
for ($j = 0; $j < $n; $j++)
$arr[$j] = $arr[$j] - 1;
// Use every element arr[i]
// as index and add 'n' to
// element present at arr[i]%n
// to keep track of count of
// occurrences of arr[i]
for ($i = 0; $i < $n; $i++)
$arr[$arr[$i] % $n] =
$arr[$arr[$i] % $n] + $n;
// To print counts, simply
// print the number of times
// n was added at index
// corresponding to every element
for ($i = 0; $i < $n; $i++)
echo $i + 1, " -> " ,
(int)($arr[$i] / $n) , "\n";
}
// Driver Code
$arr = array(2, 3, 3, 2, 5);
$n = sizeof($arr);
printfrequency($arr,$n);
// This code is contributed by ajit
?>
Output1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
Time Complexity: O(n). Only two traversals of the array are needed and a single traversal of the array takes O(n) time.
Auxiliary Space: O(1). Since no extra space is needed.
Similar Reads
Count frequencies of all elements in array in Python using collections module
Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array. Examples: Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] Output : 1 -> 4 2 -> 4 3 -> 2 4 -> 1 5 -> 2 This problem can be solved in many ways, refer
2 min read
Find duplicate in an array in O(n) and by using O(1) extra space
Given an array arr[] containing n integers where each integer is between 1 and (n-1) (inclusive). There is only one duplicate element, find the duplicate element in O(n) time complexity and O(1) space. Examples : Input : arr[] = {1, 4, 3, 4, 2} Output : 4Input : arr[] = {1, 3, 2, 1}Output : 1Recomme
13 min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeatin
10 min read
Duplicates in an array in O(n) and by using O(1) extra space | Set-2
Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers. Note: The repeating element should be printed only once. Example: Input: n = 7, arr[] = [1, 2, 3, 6, 3, 6, 1]Output: 1, 3, 6Exp
6 min read
Count of index pairs with equal elements in an array | Set 2
Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
8 min read
Count of elements of an array present in every row of NxM matrix
Given N rows with M elements each and an array arr[] of L numbers, the task is to print the count of elements of that array present in every row of the matrix. Examples: Input: {8 27 39 589 23 23 34 589 12 45 939 32 27 12 78 23 349 48 21 32}, arr[] = {589, 39, 27} Output: 1st row - 3 2nd row - 1 3rd
7 min read
Javascript program for counting frequencies of array elements
Here are the various approaches to count the frequencies of array elements in JavaScript. Using an Object (Simple and Efficient)This is the most common approach for counting frequency in an array. Each array element becomes a key in the object, and its value is incremented as the element appears. [G
2 min read
Count of elements in given Array divisible by all elements in their prefix
Given an array arr[] containing N positive integers, the task is to find the total number of elements in the array that are divisible by all the elements present before them. Examples: Input: arr[] = {10, 6, 60, 120, 30, 360}Output: 3Explanation: 60, 120 and 360 are the required elements. Input: arr
12 min read
Find duplicates in constant array with elements 0 to N-1 in O(1) space
Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is
12 min read
Counting frequencies of array elements
Given an array which may contain duplicates, print all elements and their frequencies. Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}Output : 10 3 20 4 5 1Input : arr[] = {10, 20, 20}Output : 10 1 20 2 A simple solution is to run two loops. For every item count number of times, it occurs.
15+ min read