11const LinkedList = require ( './linkedlist' ) ;
22
3- LinkedList . prototype . findKthToLast = function ( k ) {
4- let length = 0 ;
5- for ( let n = this . head ; n ; n = n . next ) { length ++ ; }
6-
7- if ( k < 1 || k > length ) {
8- return null ;
9- }
103
11- let node = this . head ;
12- for ( let i = 0 ; i < length - k ; i ++ ) { node = node . next ; }
13- return node . data ;
14- } ;
4+ LinkedList . prototype . findKthToLast = optimal ;
5+ // LinkedList.prototype.findKthToLast = mySolution;
6+ // LinkedList.prototype.findKthToLast = recursive;
157
168let list = new LinkedList ( ) ;
179list . add ( 4 ) ;
@@ -21,9 +13,81 @@ list.add(1);
2113
2214console . log ( list . toString ( ) ) ; //
2315
24- console . log ( list . findKthToLast ( 0 ) ) ; // null
16+ console . log ( list . findKthToLast ( 0 ) ) ; // undefined
2517console . log ( list . findKthToLast ( 1 ) ) ; // 4
2618console . log ( list . findKthToLast ( 2 ) ) ; // 3
2719console . log ( list . findKthToLast ( 3 ) ) ; // 2
2820console . log ( list . findKthToLast ( 4 ) ) ; // 1
29- console . log ( list . findKthToLast ( 5 ) ) ; // null
21+ console . log ( list . findKthToLast ( 5 ) ) ; // undefined
22+
23+
24+ // -----------------------
25+
26+ /**
27+ *
28+ * @param k
29+ * @returns {* }
30+ */
31+ function optimal ( k ) {
32+ let kth ;
33+ let last = this . head ;
34+
35+ // move ahead "last" k-spaces ahead
36+ for ( let i = 0 ; i < k ; i ++ ) {
37+ if ( ! last ) { return ; }
38+ last = last . next ;
39+ }
40+
41+ // move both together
42+ for ( kth = this . head ; last ; last = last . next , kth = kth . next ) { }
43+ return kth && kth . data ;
44+ }
45+
46+ /**
47+ *
48+ *
49+ * O (n) and O(n) space
50+ * @param k
51+ * @param n
52+ * @param i
53+ * @returns {* }
54+ */
55+ function recursive ( k , n = this . head , i = 0 ) {
56+ if ( n ) {
57+ let res = recursive ( k , n . next , i + 1 ) ;
58+
59+ if ( res . index === i ) {
60+ res . node = n . data ;
61+ }
62+
63+ if ( i === 0 ) {
64+ return res . node ;
65+ } else {
66+ return res ;
67+ }
68+ } else {
69+ return { node : undefined , index : i - k } ;
70+ }
71+ }
72+
73+
74+ /**
75+ * Do two rounds one to count and other one to return the kth value from last
76+ *
77+ * O(n)
78+ *
79+ * @param k
80+ * @returns {* }
81+ */
82+ function mySolution ( k ) {
83+ let length = 0 ;
84+ for ( let n = this . head ; n ; n = n . next ) { length ++ ; }
85+
86+ if ( k < 1 || k > length ) {
87+ return ;
88+ }
89+
90+ let node = this . head ;
91+ for ( let i = 0 ; i < length - k ; i ++ ) { node = node . next ; }
92+ return node . data ;
93+ } ;
0 commit comments