Count of numbers smaller than X

 find the numbers which are smaller than equal to the number x

Example 1:

Input: 
N = 5
Arr[] = {9, 7, 5, 1, 2}
X = 6
Output: 3
Explanation: 5, 1, 2 are smaller than 6

Example 2:

Input: 
N = 6
Arr[] = {1, 3, 3, 2, 5, 7, 6 }
X = 3
Output: 4
Explanation: 1, 3, 3, 2 are smaller than equal than 3

 


method 1:

Initializes a counter variable count to 0. For each element in the array, if the element is less than or equal to x, the counter variable count is incremented by 1. After the loop, the final value of the count variable is returned.


Java implementation:

class Codemummy { public long countOfElements(long a[], long n, long x) { long count=0; for(int i=0;i<n;i++){ if(a[i]<=x){ count++; } } return count; } }

 Time Complexity: O(n).
Auxiliary Space: O(1).



C++ implementation:


long countOfElements(long a[], long n, long x) {
    long count=0;
    for(int i=0;i<n;i++) {
        if(a[i]<=x) {
            count++;  
        }
    }
    return count;
}

 Time Complexity: O(n).
Auxiliary Space: O(1).



python implementation:


def countOfElements(a, n, x):
    count = 0
    for i in range(n):
        if a[i] <= x:
            count += 1  
    return count

 Time Complexity: O(n).
Auxiliary Space: O(1).

No comments

darkmode