Kth Distinct String in an Array - Problem
Imagine you're organizing a library catalog where you need to find the kth unique book title that appears exactly once in your collection.
A distinct string is a string that appears exactly once in an array. Given an array of strings arr and an integer k, your task is to return the kth distinct string present in the array, maintaining the original order of appearance.
Key Points:
- Strings are considered in the order they appear in the array
- Only count strings that appear exactly once
- If there are fewer than
kdistinct strings, return an empty string""
Example: In ["apple", "banana", "apple", "cherry", "date"], the distinct strings are ["banana", "cherry", "date"] in that order.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = ["d","b","c","b","c","a"], k = 2
โบ
Output:
"a"
๐ก Note:
The distinct strings are "d" and "a". "d" appears first (1st distinct), and "a" appears second (2nd distinct), so we return "a".
example_2.py โ Not Enough Distinct
$
Input:
arr = ["aaa","aa","a"], k = 1
โบ
Output:
"aaa"
๐ก Note:
All strings are distinct (each appears exactly once), so the 1st distinct string is "aaa".
example_3.py โ No Distinct Strings
$
Input:
arr = ["a","b","a"], k = 3
โบ
Output:
""
๐ก Note:
Only "b" is distinct (appears once), but we need the 3rd distinct string. Since there's only 1 distinct string, return empty string.
Constraints
- 1 โค arr.length โค 1000
- 1 โค k โค arr.length
- 1 โค arr[i].length โค 5
- arr[i] consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Catalog All Books
Walk through shelf and create a catalog noting how many copies of each title exist
2
Identify Unique Titles
Go through shelf again, marking titles that appear exactly once
3
Find Kth Unique
Count unique titles in order until reaching the kth one
Key Takeaway
๐ฏ Key Insight: We need to count frequencies first because a string's uniqueness depends on its total occurrences across the entire array.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code