@@ -42,9 +42,69 @@ function non_repeat_substring(str) {
42
42
return maxLength ;
43
43
}
44
44
45
- console . log ( non_repeat_substring ( "aabccbb" ) ) ;
46
- console . log ( non_repeat_substring ( "abbbb" ) ) ;
47
- console . log ( non_repeat_substring ( "abccde" ) ) ;
45
+ // console.log(non_repeat_substring("aabccbb"));
46
+ // console.log(non_repeat_substring("abbbb"));
47
+ // console.log(non_repeat_substring("abccde"));
48
+ console . log ( non_repeat_substring ( "abcdaefghijkl" ) , "#0" ) ;
49
+
50
+ // -------- Alternate Solution ----------
51
+ // The above solution algo fails for last testcase. The 2 solutions below are correct.
52
+
53
+ // Solution 1
54
+ function noRepeatCharLen1 ( str ) {
55
+ let j = 0 ;
56
+ let i = 0 ;
57
+ const frequencyTracker = { } ;
58
+ let longestSubStrLen = 0 ;
59
+
60
+ while ( j < str . length ) {
61
+ if ( ! frequencyTracker . hasOwnProperty ( str [ j ] ) ) {
62
+ frequencyTracker [ str [ j ] ] = 1 ;
63
+ longestSubStrLen = Math . max ( longestSubStrLen , j - i + 1 ) ;
64
+ } else {
65
+ frequencyTracker [ str [ j ] ] ++ ;
66
+ }
67
+
68
+ while ( frequencyTracker [ str [ j ] ] > 1 ) {
69
+ frequencyTracker [ str [ i ] ] --
70
+ if ( frequencyTracker [ str [ i ] ] === 0 ) {
71
+ delete frequencyTracker [ str [ i ] ] ;
72
+ }
73
+
74
+ i ++ ;
75
+ }
76
+
77
+ j ++ ;
78
+ } ;
79
+
80
+ return longestSubStrLen ;
81
+ }
82
+
83
+ // Solution #2
84
+ function noRepeatCharLen2 ( str ) {
85
+ let windowStart = 0 ,
86
+ maxLength = 0 ,
87
+ charIndexMap = { } ;
88
+
89
+ for ( let windowEnd = 0 ; windowEnd < str . length ; windowEnd ++ ) {
90
+ const rightChar = str [ windowEnd ] ;
91
+
92
+ if ( rightChar in charIndexMap ) {
93
+ windowStart = Math . max ( windowStart , charIndexMap [ rightChar ] + 1 ) ;
94
+ }
95
+
96
+ charIndexMap [ rightChar ] = windowEnd ;
97
+
98
+ maxLength = Math . max ( maxLength , windowEnd - windowStart + 1 ) ;
99
+ }
100
+
101
+ return maxLength ;
102
+ }
103
+
104
+ console . log ( noRepeatCharLen1 ( "abcdaefghijkl" ) , "#1" ) ;
105
+ console . log ( noRepeatCharLen2 ( "abcdaefghijkl" ) , "#2" ) ;
106
+
107
+ // a b c d a e f g h i j k l
48
108
49
109
/*
50
110
Time Complexity #
0 commit comments