Kth Distinct String in an Array

Kth Distinct String in an Array

A distinct string is a string that is present only once in an array.

Given an array of strings arr, and an integer k, return the k<sup>th</sup> distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".

Note that the strings are considered in the order in which they appear in the array.

LeetCode Problem - 2053

class Solution {
    // This method returns the kth distinct element in the array `arr`.
    public String kthDistinct(String[] arr, int k) {
        // HashMap to store the frequency of each element in the array
        HashMap<String, Integer> hm = new HashMap<>();

        // Count the frequency of each element in the array
        for (String str : arr) {
            hm.put(str, hm.getOrDefault(str, 0) + 1);
        }

        // Variable to track the count of distinct elements encountered
        int flag = 0;

        // Iterate through each element in the array
        for (String str : arr) {
            // If the current element has a frequency of 1, it is distinct
            if (hm.get(str) == 1)
                flag++;

            // If we have encountered the kth distinct element, return it
            if (flag == k)
                return str;
        }
        // If kth distinct element is not found, return an empty string
        return "";
    }
}