The problem is to find the kth distinct string in an array. A distinct string is a string that appears exactly once in the array. You need to return the kth distinct string in the array. If there are fewer than k distinct strings, return an empty string ""
.
Example:
Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
Explanation: The only distinct strings in the array are "d" and "a". Return "a" since it is the 2nd distinct string.
arr
?Assumptions based on common LeetCode constraints:
- The length of `arr` is in the range [1, 1000].
- Each string in `arr` has a length in the range [1, 100].
- The strings consist of lowercase English letters.
k
distinct strings, return ""
.k
is larger than the number of distinct strings?arr
has only one element?To solve this problem, we can use the following strategy:
def kthDistinct(arr, k):
count = {}
# Count the occurrences of each string
for string in arr:
if string in count:
count[string] += 1
else:
count[string] = 1
# Collect the distinct strings
distinct_strings = [string for string in arr if count[string] == 1]
# Return the kth distinct string (1-indexed)
if k <= len(distinct_strings):
return distinct_strings[k - 1]
return ""
# Example usage:
arr = ["d", "b", "c", "b", "c", "a"]
k = 2
print(kthDistinct(arr, k)) # Output: "a"
n
is the length of the array arr
. We iterate through the array once to count the occurrences of each string.This approach ensures that we efficiently find the kth distinct string with clear steps and meets the problem requirements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?