2053. Kth Distinct String in an Array (Leetcode Badge)

preview_player
Показать описание
Top 1 Leetcoder In The World Explains Easiest Solution In 3 Minutes | C++ | Java | Python
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
2053 Kth Distinct String in an Array Of Leetcode Badge.
Very Easy Solution
Рекомендации по теме
Комментарии
Автор

C++ Code:

class Solution {
public:
string kthDistinct(vector<string>& arr, int k) {
//map
unordered_map<string, int> counter;
//counting elements and incrementing in map
for(int i=0;i<arr.size();i++){
counter[arr[i]]++;
}
//checking the distinct elements and seeing their placement
int cnt=0;
for(int i=0;i<arr.size();i++){
if(counter[arr[i]]==1){
cnt++;
}
if(cnt==k){
return arr[i];
}
}
return "";
}
};

Algorizz
Автор

Java Code:

class Solution {
public String kthDistinct(String[] arr, int k) {
//map
HashMap<String, Integer> counter = new HashMap<>();
//counting elements and incrementing in map
for (String s : arr) {
counter.put(s, counter.getOrDefault(s, 0) + 1);
}
//checking the distinct elements and seeing their placement
int cnt = 0;
for (String s : arr) {
if (counter.get(s) == 1) {
cnt++;
}
if (cnt == k) {
return s;
}
}
return "";
}
}

Algorizz
Автор

Python Code:

class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
# maping the count of elements
counter = Counter(arr)
# checking for distinct elements and seeing their placement
cnt = 0
for item in arr:
if counter[item] == 1:
cnt += 1
if cnt == k:
return item

return ""

Algorizz
welcome to shbcf.ru