Given an unsorted array arr[]. Find the count of elements less than or equal to the given element x.
Examples:
Input: x = 9, arr[] = [10, 1, 2, 8, 4, 5]
Output: 5
Explanation: The 5 elements are 1, 2, 8, 4 and 5.Input: x = 2, arr[] = [1, 2, 2, 5, 7, 2, 9]
Output: 4
Explanation: The 4 elements are 1, 2, 2 and 2.
Using Linear Traversal - O(n) Time and O(1) Space
The idea is to traverse the array once and count every element that is less than or equal to x. Since we only need the count, there is no need to sort the array.
Working of the Approach:
- Initialize a count variable as 0.
- Traverse every element of the array.
- If the current element is <= x, increment the count.
- Return the final count.
Let us understand with an example:
Input: x = 2, arr[] = [1, 2, 2, 5, 7, 2, 9]
- Initialize cnt = 0. Traverse the array: 1 <= 2 -> cnt = 1, 2 <= 2 -> cnt = 2, 2 <= 2 -> cnt = 3.
- Continue traversal: 5 > 2, 7 > 2, so cnt remains 3.
- For the next element, 2 <= 2 -> cnt = 4, and 9 > 2, so cnt remains 4.
- Return cnt = 4, which is the count of elements less than or equal to x.
#include <iostream>
#include <vector>
using namespace std;
int countOfElements(int x, vector<int> &arr)
{
int n = arr.size();
// Initialize count variable
int cnt = 0;
// Iterate through the array
for (int i = 0; i < n; i++)
{
if (arr[i] <= x)
cnt++;
}
return cnt;
}
int main()
{
vector<int> arr = {1, 2, 2, 5, 7, 2, 9};
int x = 2;
cout << countOfElements(x, arr);
return 0;
}
import java.util.*;
class GFG {
public int countOfElements(int x, List<Integer> arr)
{
int n = arr.size();
// Initialize count variable
int cnt = 0;
// Iterate through the array
for (int i = 0; i < n; i++) {
if (arr.get(i) <= x)
cnt++;
}
return cnt;
}
public static void main(String[] args)
{
List<Integer> arr
= Arrays.asList(1, 2, 2, 5, 7, 2, 9);
int x = 2;
GFG obj = new GFG();
System.out.println(obj.countOfElements(x, arr));
}
}
def countOfElements(x, arr):
# Initialize count variable
cnt = 0
# Iterate through the array
for i in arr:
if i <= x:
cnt += 1
return cnt
if __name__ == '__main__':
arr = [1, 2, 2, 5, 7, 2, 9]
x = 2
print(countOfElements(x, arr))
using System;
class GFG {
public int countOfElements(int x, int[] arr)
{
int n = arr.Length;
// Initialize count variable
int cnt = 0;
// Iterate through the array
for (int i = 0; i < n; i++) {
if (arr[i] <= x)
cnt++;
}
return cnt;
}
public static void Main()
{
int[] arr = { 1, 2, 2, 5, 7, 2, 9 };
int x = 2;
GFG obj = new GFG();
Console.WriteLine(obj.countOfElements(x, arr));
}
}
function countOfElements(x, arr)
{
// Initialize count variable
let cnt = 0;
// Iterate through the array
for (let i = 0; i < arr.length; i++) {
if (arr[i] <= x)
cnt++;
}
return cnt;
}
// Driver Code
let arr = [ 1, 2, 2, 5, 7, 2, 9 ];
let x = 2;
console.log(countOfElements(x, arr));
Output
4