LeetCode 2053: Kth Distinct String in an Array Solution

Master LeetCode problem 2053 (Kth Distinct String in an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2053. Kth Distinct String in an Array

Problem Explanation

Explanation

To solve this problem, we can iterate through the array of strings and keep track of the count of each string using a HashMap. We will also maintain the order of appearance of the strings using a LinkedHashSet. After processing all strings, we can iterate over the LinkedHashSet to find the kth distinct string.

  • We iterate through the input array and store the count of each string in a HashMap.
  • We also maintain a LinkedHashSet to keep track of the order of appearance of the strings.
  • After processing all strings, we iterate over the LinkedHashSet to find the kth distinct string. If there are fewer than k distinct strings, we return an empty string.

Time Complexity

The time complexity of this approach is O(n), where n is the number of strings in the input array.

Space Complexity

The space complexity of this approach is O(n) as we are using a HashMap and a LinkedHashSet to store the strings.

Solution Code

import java.util.*;

class Solution {
    public String kthDistinctString(String[] arr, int k) {
        Map<String, Integer> countMap = new HashMap<>();
        Set<String> distinctStrings = new LinkedHashSet<>();
        
        for (String str : arr) {
            countMap.put(str, countMap.getOrDefault(str, 0) + 1);
            if (countMap.get(str) == 1) {
                distinctStrings.add(str);
            } else {
                distinctStrings.remove(str);
            }
        }
        
        if (distinctStrings.size() < k) {
            return "";
        }
        
        Iterator<String> iterator = distinctStrings.iterator();
        String result = "";
        for (int i = 0; i < k; i++) {
            result = iterator.next();
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2053 (Kth Distinct String in an Array)?

This page provides optimized solutions for LeetCode problem 2053 (Kth Distinct String in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2053 (Kth Distinct String in an Array)?

The time complexity for LeetCode 2053 (Kth Distinct String in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2053 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2053 in Java, C++, or Python.

Back to LeetCode Solutions