Skip to main content

Command Palette

Search for a command to run...

Kth Distinct String in an Array

Published
1 min read
Kth Distinct String in an Array
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

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 k<sup>th</sup> 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.

LeetCode Problem - 2053

class Solution {
    // This method returns the kth distinct element in the array `arr`.
    public String kthDistinct(String[] arr, int k) {
        // HashMap to store the frequency of each element in the array
        HashMap<String, Integer> hm = new HashMap<>();

        // Count the frequency of each element in the array
        for (String str : arr) {
            hm.put(str, hm.getOrDefault(str, 0) + 1);
        }

        // Variable to track the count of distinct elements encountered
        int flag = 0;

        // Iterate through each element in the array
        for (String str : arr) {
            // If the current element has a frequency of 1, it is distinct
            if (hm.get(str) == 1)
                flag++;

            // If we have encountered the kth distinct element, return it
            if (flag == k)
                return str;
        }
        // If kth distinct element is not found, return an empty string
        return "";
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.