Post

Leetcode 2053. Kth Distinct String in an Array

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_ `""`.

Description

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 that the strings are considered in the order in which they appear in the array.

Example 1:

Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
  • The only distinct strings in arr are “d” and “a”.
    “d” appears 1st, so it is the 1st distinct string.
    “a” appears 2nd, so it is the 2nd distinct string.
    Since k == 2, “a” is returned.

Example 2:

Input: arr = ["aaa","aa","a"], k = 1
Output: "aaa"
  • All strings in arr are distinct, so the 1st string “aaa” is returned.

Example 3:

Input: arr = ["a","b","a"], k = 3
Output: ""
  • The only distinct string is “b”. Since there are fewer than 3 distinct strings, we return an empty string “”.

Constraints:

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Solution {
    public String kthDistinct(String[] arr, int k) {

        List<String> all = new ArrayList<String>();
        List<String> dist = new ArrayList<String>();
        String str = "";

        for (int i = 0; i < arr.length; i++) {
            if (dist.contains(arr[i]) && all.contains(arr[i])) {
                dist.remove(arr[i]);
            }
            else if (dist.contains(arr[i]) == false && all.contains(arr[i])) {
                continue;
            }
            else {
                dist.add(arr[i]);
                all.add(arr[i]);
            }
        }

        if (dist.size() >= k) {
            str = dist.get(k - 1);
        }

        return str;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import Counter

class Solution:
    # Iteration
    # Time Complexity: BigO(N)
    # Space Complexity: BigO(N)
    def kthDistinct(self, arr: List[str], k: int) -> str:
        dist_list = Counter(arr)

        for str in dist_list:
            if dist_list[str] == 1:
                k -= 1
            if k == 0:
                return str

        return ""
This post is licensed under CC BY 4.0 by the author.