Kth Distinct String in an Array
Let’s understand how to find the kth distinct string from the given array of strings, and then write code.
Approach
Create a Counter: Use a dictionary to count the frequency of each string in the array.
Find kth Distinct String: Iterate through the array, and for each string that appears only once, reduce the value of
k
. Whenk
reaches 0, return the string at that position, as it is the kth distinct string.Handle Edge Cases: If there are fewer than
k
distinct strings, return an empty string""
.
Example Code
|
|
Explanation
- For
arr = ["d","b","c","b","c","a"]
andk = 2
, the counter will be{'d': 1, 'b': 2, 'c': 2, 'a': 1}
. - When iterating through the array, the first distinct string is “d” and the second distinct string is “a”. Since
k = 2
, we return “a”.
Key Takeaways
- The solution counts the frequency of each string and then iterates through the array to find the kth distinct string.
- It ensures to handle the case where there are fewer than
k
distinct strings by returning an empty string. - This approach is simple and adheres to the problem constraints, considering strings in the order they appear in the array.