File tree Expand file tree Collapse file tree 5 files changed +115
-0
lines changed
kth-smallest-element-in-a-bst Expand file tree Collapse file tree 5 files changed +115
-0
lines changed Original file line number Diff line number Diff line change 1+ // TC: O(N)
2+ // SC: O(N)
3+
4+ /**
5+ * @param {number[] } nums
6+ * @return {boolean }
7+ */
8+ var containsDuplicate = function ( nums ) {
9+ return nums . length !== new Set ( nums ) . size ;
10+ } ;
Original file line number Diff line number Diff line change 1+ // TC: O(N)
2+ // SC: O(N)
3+
4+ /**
5+ * Definition for a binary tree node.
6+ * function TreeNode(val, left, right) {
7+ * this.val = (val===undefined ? 0 : val)
8+ * this.left = (left===undefined ? null : left)
9+ * this.right = (right===undefined ? null : right)
10+ * }
11+ */
12+ /**
13+ * @param {TreeNode } root
14+ * @param {number } k
15+ * @return {number }
16+ */
17+ var kthSmallest = function ( root , k ) {
18+ let result = null ;
19+
20+ dfs ( root ) ;
21+
22+ return result ;
23+
24+ function dfs ( current ) {
25+ if ( result !== null ) {
26+ return ;
27+ }
28+ if ( ! current ) {
29+ return ;
30+ }
31+
32+ dfs ( current . left ) ;
33+ if ( current . val >= 0 ) {
34+ if ( k === 1 ) {
35+ result = current . val ;
36+ }
37+ k -= 1 ;
38+ }
39+ dfs ( current . right ) ;
40+ }
41+ } ;
Original file line number Diff line number Diff line change 1+ // TC: O(log n)
2+ // SC: O(1)
3+
4+ /**
5+ * @param {number } n
6+ * @return {number }
7+ */
8+ var hammingWeight = function ( n ) {
9+ return n
10+ . toString ( 2 )
11+ . split ( "" )
12+ . filter ( ( s ) => s === "1" ) . length ;
13+ } ;
Original file line number Diff line number Diff line change 1+ // TC: O(n^3)
2+ // SC: O(1)
3+
4+ /**
5+ * @param {string } s
6+ * @return {number }
7+ */
8+ var countSubstrings = function ( s ) {
9+ let count = 0 ;
10+
11+ for ( let left = 0 ; left < s . length ; left ++ ) {
12+ for ( let right = left ; right < s . length ; right ++ ) {
13+ if ( checkIsPalinDrome ( left , right ) ) {
14+ count += 1 ;
15+ }
16+ }
17+ }
18+
19+ return count ;
20+
21+ function checkIsPalinDrome ( left , right ) {
22+ while ( left < right ) {
23+ if ( s [ left ] !== s [ right ] ) {
24+ return false ;
25+ }
26+ left += 1 ;
27+ right -= 1 ;
28+ }
29+
30+ return true ;
31+ }
32+ } ;
Original file line number Diff line number Diff line change 1+ // TC: O(n logn)
2+ // SC: O(N)
3+
4+ /**
5+ * @param {number[] } nums
6+ * @param {number } k
7+ * @return {number[] }
8+ */
9+ var topKFrequent = function ( nums , k ) {
10+ const numAndCountBoard = nums . reduce ( ( result , current ) => {
11+ result [ current ] = result . hasOwnProperty ( current ) ? result [ current ] + 1 : 1 ;
12+ return result ;
13+ } , { } ) ;
14+
15+ return Object . entries ( numAndCountBoard )
16+ . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] )
17+ . slice ( 0 , k )
18+ . map ( ( element ) => element [ 0 ] ) ;
19+ } ;
You can’t perform that action at this time.
0 commit comments