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 in an Array INPUT arr = ["d","b","c","b","c","a"] "d" 0 "b" 1 "c" 2 "b" 3 "c" 4 "a" 5 k = 2 Find the 2nd string that appears exactly once in the array Distinct = appears only once Order matters (left to right) ALGORITHM STEPS 1 Count Frequencies Hash map: string --> count "d": 1 "b": 2 "c": 2 "a": 1 2 Filter Distinct Keep strings with count = 1 "d" "a" 3 Maintain Order Scan array in order 1st distinct: "d" (idx 0) 2nd distinct: "a" (idx 5) 4 Return k-th k=2 --> return "a" FINAL RESULT Distinct strings in order: "d" 1st "a" 2nd Output: "a" OK - Verified "a" is 2nd distinct Time: O(n) Space: O(n) Key Insight: Use a hash map to count occurrences in O(n), then iterate through the original array to find distinct strings (count = 1) in their original order. Return the k-th one found. TutorialsPoint - Kth Distinct String in an Array | Hash Map Approach
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