File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * Author: Mayank
3+ * Minimum Window Substring implementation in JavaScript
4+ * Finds the smallest substring of s that contains all characters of t.
5+ */
6+
7+ function minWindowSubstring ( s , t ) {
8+ if ( t . length > s . length ) return ""
9+
10+ const need = { }
11+ for ( let char of t ) {
12+ need [ char ] = ( need [ char ] || 0 ) + 1
13+ }
14+
15+ let left = 0
16+ let count = t . length
17+ let minLen = Infinity
18+ let minStart = 0
19+
20+ for ( let right = 0 ; right < s . length ; right ++ ) {
21+ if ( need [ s [ right ] ] !== undefined ) {
22+ if ( need [ s [ right ] ] > 0 ) count --
23+ need [ s [ right ] ] --
24+ }
25+
26+ while ( count === 0 ) {
27+ if ( right - left + 1 < minLen ) {
28+ minLen = right - left + 1
29+ minStart = left
30+ }
31+ if ( need [ s [ left ] ] !== undefined ) {
32+ need [ s [ left ] ] ++
33+ if ( need [ s [ left ] ] > 0 ) count ++
34+ }
35+ left ++
36+ }
37+ }
38+
39+ return minLen === Infinity ? "" : s . substring ( minStart , minStart + minLen )
40+ }
41+
42+ export { minWindowSubstring }
Original file line number Diff line number Diff line change 1+ /*
2+ * Test file for Minimum Window Substring
3+ */
4+
5+ import { minWindowSubstring } from "../MinimumWindowSubstring.js"
6+
7+ test ( "return smallest window containing all characters" , ( ) => {
8+ expect ( minWindowSubstring ( "ADOBECODEBANC" , "ABC" ) ) . toBe ( "BANC" )
9+ } )
10+
11+ test ( "return empty string if no window found" , ( ) => {
12+ expect ( minWindowSubstring ( "HELLO" , "XYZ" ) ) . toBe ( "" )
13+ } )
14+
15+ test ( "return full string if it matches exactly" , ( ) => {
16+ expect ( minWindowSubstring ( "ABC" , "ABC" ) ) . toBe ( "ABC" )
17+ } )
You can’t perform that action at this time.
0 commit comments