File tree Expand file tree Collapse file tree 3 files changed +54
-2
lines changed
solution/2000-2099/2053.Kth Distinct String in an Array Expand file tree Collapse file tree 3 files changed +54
-2
lines changed Original file line number Diff line number Diff line change @@ -151,6 +151,25 @@ func kthDistinct(arr []string, k int) string {
151
151
}
152
152
```
153
153
154
+ #### TypeScript
155
+
156
+ ``` ts
157
+ function kthDistinct(arr : string [], k : number ): string {
158
+ const cnt = new Map <string , number >();
159
+
160
+ for (const x of arr ) {
161
+ cnt .set (x , (cnt .get (x ) ?? 0 ) + 1 );
162
+ }
163
+
164
+ for (const [x, c] of cnt ) {
165
+ if (c === 1 ) k -- ;
166
+ if (! k ) return x ;
167
+ }
168
+
169
+ return ' ' ;
170
+ }
171
+ ```
172
+
154
173
<!-- tabs: end -->
155
174
156
175
<!-- solution: end -->
Original file line number Diff line number Diff line change 37
37
The only distinct strings in arr are " ; d" ; and " ; a" ; .
38
38
" ; d" ; appears 1<sup >st</sup >, so it is the 1<sup >st</sup > distinct string.
39
39
" ; a" ; appears 2<sup >nd</sup >, so it is the 2<sup >nd</sup > distinct string.
40
- Since k == 2, " ; a" ; is returned.
40
+ Since k == 2, " ; a" ; is returned.
41
41
</pre >
42
42
43
43
<p ><strong class =" example " >Example 2:</strong ></p >
@@ -73,7 +73,7 @@ The only distinct string is "b". Since there are fewer than 3 distinct
73
73
74
74
<!-- solution:start -->
75
75
76
- ### Solution 1
76
+ ### Solution 1: Counting
77
77
78
78
<!-- tabs:start -->
79
79
@@ -152,6 +152,25 @@ func kthDistinct(arr []string, k int) string {
152
152
}
153
153
```
154
154
155
+ #### TypeScript
156
+
157
+ ``` ts
158
+ function kthDistinct(arr : string [], k : number ): string {
159
+ const cnt = new Map <string , number >();
160
+
161
+ for (const x of arr ) {
162
+ cnt .set (x , (cnt .get (x ) ?? 0 ) + 1 );
163
+ }
164
+
165
+ for (const [x, c] of cnt ) {
166
+ if (c === 1 ) k -- ;
167
+ if (! k ) return x ;
168
+ }
169
+
170
+ return ' ' ;
171
+ }
172
+ ```
173
+
155
174
<!-- tabs: end -->
156
175
157
176
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ function kthDistinct ( arr : string [ ] , k : number ) : string {
2
+ const cnt = new Map < string , number > ( ) ;
3
+
4
+ for ( const x of arr ) {
5
+ cnt . set ( x , ( cnt . get ( x ) ?? 0 ) + 1 ) ;
6
+ }
7
+
8
+ for ( const [ x , c ] of cnt ) {
9
+ if ( c === 1 ) k -- ;
10
+ if ( ! k ) return x ;
11
+ }
12
+
13
+ return '' ;
14
+ }
You can’t perform that action at this time.
0 commit comments