Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit cef3857

Browse files
committedDec 24, 2021
solves kth distinct string in array
1 parent d5291f8 commit cef3857

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed
 

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@
488488
| 2037 | [Minimum Number of Moves to Seat Everyone](https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone) | [![Java](assets/java.png)](src/MinimumNumberOfMovesToSeatEveryone.java) | |
489489
| 2042 | [Check if Numbers Are Ascending in a Sentence](https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence) | [![Java](assets/java.png)](src/CheckIfNumbersAreAscendingInASentence.java) | |
490490
| 2047 | [Number of Valid Words in a Sentence](https://leetcode.com/problems/number-of-valid-words-in-a-sentence) | [![Java](assets/java.png)](src/NumberOfValidWordsInASentence.java) | |
491-
| 2053 | [Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array) | | |
491+
| 2053 | [Kth Distinct String in an Array](https://leetcode.com/problems/kth-distinct-string-in-an-array) | [![Java](assets/java.png)](src/KthDistinctStringInAnArray.java) | |
492492
| 2057 | [Smallest Index With Equal Value](https://leetcode.com/problems/smallest-index-with-equal-value) | | |
493493
| 2062 | [Count Vowel Substrings of a String](https://leetcode.com/problems/count-vowel-substrings-of-a-string) | | |
494494
| 2068 | [Check Whether Two Strings are Almost Equivalent](https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent) | | |

‎src/KthDistinctStringInAnArray.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// https://leetcode.com/problems/kth-distinct-string-in-an-array
2+
// T: O(|arr|)
3+
// S: O(|arr|)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class KthDistinctStringInAnArray {
9+
public String kthDistinct(String[] arr, int k) {
10+
final Map<String, Integer> frequencies = getFrequency(arr);
11+
for (String s : arr) {
12+
if (frequencies.get(s) == 1) {
13+
k--;
14+
}
15+
if (k == 0) return s;
16+
}
17+
return "";
18+
}
19+
20+
private Map<String, Integer> getFrequency(String[] array) {
21+
final Map<String, Integer> frequencies = new HashMap<>();
22+
for (String s : array) {
23+
frequencies.put(s, frequencies.getOrDefault(s, 0) + 1);
24+
}
25+
return frequencies;
26+
}
27+
}

0 commit comments

Comments
 (0)
Please sign in to comment.