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 k distinct 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
๐Ÿ“š Library Catalog: Finding Kth Distinct BookBookshelf (Array):Book ABook BBook ABook CBook D๐Ÿ“‹ Step 1: Catalog (Count Frequencies)Book A: 2 copiesBook B: 1 copy โœ“Book C: 1 copy โœ“Book D: 1 copy โœ“๐ŸŽฏ Step 2: Find Distinct Books (in order)Book B1stBook C2ndBook D3rdIf k=2, return "Book C" (2nd distinct book in order)โฐ Time: O(n) - Two passes through the shelf๐Ÿ’พ Space: O(n) - Catalog storage
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.
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
18.6K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen