Wednesday 20 December 2023

Count Frequency in a range

Coding Ninjas Link


import java.util.HashMap;

public class Solution {

    public static int[] countFrequency(int n, int x, int []nums){

        HashMap<Integer,Integer> mp = new HashMap<>();

        int result[] = new int[n];

        for(int i=0; i<nums.length; i++)

        {

            int freq = 0;

            if(mp.containsKey(nums[i])) 

            {

                freq = mp.get(nums[i]);

            }

            freq += 1;

            mp.put(nums[i],freq);

        }

        for (int i = 0; i < n+1; i++) {

            mp.putIfAbsent(i, 0);

        }

        for(int i=0; i<n; i++)

        {

            result[i] = mp.get(i+1);

        }

        return result;

    }

}

No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...