File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
encode-and-decode-strings Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ /**
3+ * @param {string[] } strs
4+ * @returns {string }
5+ */
6+ encode ( strs ) {
7+ let result = "" ;
8+ for ( let str of strs ) {
9+ result += str . length . toString ( ) + "#" + str ;
10+ }
11+ return result ;
12+ }
13+
14+ /**
15+ * @param {string } str
16+ * @returns {string[] }
17+ */
18+ decode ( str ) {
19+ let result = [ ] ;
20+ let i = 0 ;
21+
22+ while ( i < str . length ) {
23+ // Find the position of the next '#'
24+ let j = i ;
25+ while ( str [ j ] !== "#" ) {
26+ j ++ ;
27+ }
28+
29+ // Length of the next string
30+ const len = parseInt ( str . slice ( i , j ) ) ;
31+ i = j + 1 ; // Move past the '#'
32+
33+ // Extract the string of length 'len'
34+ result . push ( str . slice ( i , i + len ) ) ;
35+ i += len ; // Move past the extracted string
36+ }
37+
38+ return result ;
39+ }
40+ }
41+
42+ // TC: O(n),O(n)
43+ // SC: O(n),O(n)
Original file line number Diff line number Diff line change 1+ var topKFrequent = function ( nums , k ) {
2+ // 1. Hashmap { num : frequency }
3+ let map = { } ;
4+
5+ // 2. Iterate counts frequency of each value
6+ for ( num of nums ) {
7+ // Check there is already num key or not
8+ if ( ! map [ num ] ) map [ num ] = 0 ;
9+ map [ num ] ++ ;
10+ }
11+
12+ // 3. Sort frequency and return sliced array
13+ return [ ...Object . keys ( map ) ] . sort ( ( a , b ) => map [ b ] - map [ a ] ) . slice ( 0 , k ) ;
14+ } ;
You can’t perform that action at this time.
0 commit comments