2053. Kth Distinct String in an Array
- Manbodh ratre
- Aug 6, 2024
- 1 min read
#LeetCode Solution
Time Complexity O(n)
Space Complexity O(n)
Approach:
1. first store the frequency of each string into hashmap.
2. iterate over the string array and check those string which has frequency 1 count those string and if that string is kth string then return that.
3. else return empty string.
class Solution {
public String kthDistinct(String[] arr, int k) {
HashMap<String, Integer> map = new HashMap<>();
for(String str: arr){
map.put(str,map.getOrDefault(str,0)+1);
}
int count = 0;
for(String str: arr){
if(map.containsKey(str)&&map.get(str)<2){
count++;
if(count==k)
return str;
}
}
return "";
}
}
Comments