2053. Kth Distinct String in an Array
UnknownView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Kth Distinct String in an Array (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Count occurrences with a dictionary; iterate in order and return the kth string with count 1.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Count occurrences with a dictionary; iterate in order and return the kth string with count 1.
Related patterns: Array, Hash Table, String
2053.cs
C#
// Approach: Count occurrences with a dictionary; iterate in order and return the kth string with count 1.
// Time: O(n) Space: O(n)
public class Solution
{
public string KthDistinct(string[] arr, int k)
{
Dictionary<string, int> count = new Dictionary<string, int>();
foreach (var a in arr)
count[a] = count.GetValueOrDefault(a, 0) + 1;
foreach (var a in arr)
if (count[a] == 1 && --k == 0)
return a;
return string.Empty;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 15. 3Sum(Medium)