Kth Distinct String in an Array - Problem

A distinct string is a string that is present only once in an array.

Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".

Note: The strings are considered in the order in which they appear in the array.

Input & Output

Example 1 — Basic Case
$ Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
💡 Note: The distinct strings are "d" and "a" (appear only once). The 2nd distinct string is "a".
Example 2 — Not Enough Distinct
$ Input: arr = ["aaa","aa","a"], k = 1
Output: "aaa"
💡 Note: All strings are distinct (each appears once). The 1st distinct string is "aaa".
Example 3 — No kth Distinct
$ Input: arr = ["a","b","a"], k = 3
Output: ""
💡 Note: Only "b" is distinct (appears once). Since k=3 but there's only 1 distinct string, return empty string.

Constraints

  • 1 ≤ k ≤ arr.length ≤ 1000
  • 1 ≤ arr[i].length ≤ 5
  • arr[i] consists of lowercase English letters

Visualization

Tap to expand
Kth Distinct String Problem: Find 2nd DistinctInput Array:"d""b""c""b""c""a"Frequencies:d: 1b: 2c: 2a: 11st distinct2nd distinctOutput: "a" (2nd string that appears exactly once)k = 2
Understanding the Visualization
1
Input Array
Array with some duplicate strings
2
Count Frequencies
Identify which strings appear exactly once
3
Find kth Distinct
Return the kth string with frequency 1
Key Takeaway
🎯 Key Insight: Use frequency counting to identify distinct strings, then iterate in original order to find the kth one
Asked in
Amazon 25 Microsoft 18
22.0K Views
Medium Frequency
~15 min Avg. Time
850 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