top of page

2053. Kth Distinct String in an Array

#LeetCode Solution

Time Complexity O(n)

Space Complexity O(n)


Approach:

1. first store the frequency of each string into hashmap.

2. iterate over the string array and check those string which has frequency 1 count those string and if that string is kth string then return that.

3. else return empty string.

class Solution {

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

HashMap<String, Integer> map = new HashMap<>();

for(String str: arr){

map.put(str,map.getOrDefault(str,0)+1);

}

int count = 0;

for(String str: arr){

if(map.containsKey(str)&&map.get(str)<2){

count++;

if(count==k)

return str;

}

}

return "";

}

}

Recent Posts

See All

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page