Given an array of n elements, find the frequency of the smallest value in the array.
Input: [2,2,5,5,7,9,2]
Output: 3
2
is the smallest element in the given array and it appears 3
times.
We can solve this problem with two approaches.
Initialize the array arr
.
Initialize the frequency freq
with 0
.
Initialize the minimum
with the first element in the array.
Use the first loop to find out the minimum element in the array.
minimum
.minimum
.Now, the minimum
variable contains a minimum element in the array after traversing the entire array.
Use the second loop to find out occurrences of minimum element in the array.
freq
by 1.Print the freq
variable as it contains the frequency of minimum element in the array, after executing the second loop.
//initialize arraylet arr = [2,2,5,5,7,9,2]//initialize freq and minimumlet freq = 0;let minimum = arr[0];//find the minimum element in the arrayfor(let i = 1 ;i < arr.length; i++){if(arr[i] < minimum){minimum = arr[i];}}//find the frequency of minimum element resulted from above loopfor(let i = 0 ; i < arr.length ; i++){if(arr[i] == minimum){freq += 1;}}//print the frequency of minimum element in the arrayconsole.log(freq)
Initialize the array arr
.
Initialize the frequency freq
with 1
.
Initialize the minimum
with the first element in the array.
Loop through the array index 1
as we already assigned the first element to a minimum
minimum
, assign the current element to the variable minimum
, and set freq
to 1
.freq
by 1
.Now print out the freq
.
//initialize arraylet arr = [2, 2, 5, 5, 7, 9, 2]//initialize freq and minimumlet freq = 1;let minimum = arr[0];//find the minimum element in the arrayfor(let i = 1; i < arr.length ; i++){if(arr[i] < minimum){minimum = arr[i];freq = 1;}else if(arr[i] == minimum){freq += 1;}}console.log(freq)