Kth Distinct String in an Array — LeetCode 2053 Python Solution
- Problem
- #2053
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- arr = ["d","b","c","b","c","a"], k = 2
- Output
- "a"
- Explanation
- The only distinct strings in arr are "d" and "a".
Python solution
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
cnt = Counter(arr)
for s in arr:
if cnt[s] == 1:
k -= 1
if k == 0:
return s
return ""Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2053. Kth Distinct String in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2053. Kth Distinct String in an Array?
- LeetCode 2053. Kth Distinct String in an Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2053. Kth Distinct String in an Array?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2053. Kth Distinct String in an Array?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2053. Kth Distinct String in an Array cover?
- LeetCode 2053. Kth Distinct String in an Array is tagged Array, Hash Table, String and Counting on LeetCode.