How to get the frequency of smallest array value in JavaScript
Problem
Given an array of n elements, find the frequency of the smallest value in the array.
Example
Input: [2,2,5,5,7,9,2]
Output: 3
Explanation
2 is the smallest element in the given array and it appears 3 times.
Solution
We can solve this problem with two approaches.
- Using two loops
- Using one loop
Using two loops
-
Initialize the array
arr. -
Initialize the frequency
freqwith0. -
Initialize the
minimumwith the first element in the array. -
Use the first loop to find out the minimum element in the array.
- Loop through the entire array, and check if the current element is less than the value in
minimum. - If it is, then assign the current element to variable
minimum.
- Loop through the entire array, and check if the current element is less than the value in
-
Now, the
minimumvariable 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.
- Check if the current element is equal to a minimum if it is then increment the
freqby 1.
- Check if the current element is equal to a minimum if it is then increment the
-
Print the
freqvariable as it contains the frequency of minimum element in the array, after executing the second loop.
Code
//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)
Using one loop
-
Initialize the array
arr. -
Initialize the frequency
freqwith1. -
Initialize the
minimumwith the first element in the array. -
Loop through the array index
1as we already assigned the first element to a minimum- If the current element is smaller than the
minimum, assign the current element to the variableminimum, and setfreqto1. - Otherwise, if the current element is equal to a minimum then increment the
freqby1.
- If the current element is smaller than the
-
Now print out the
freq.
Code
//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)