MCPcopy Create free account
hub / github.com/ashishps1/awesome-leetcode-resources / SlidingWindow

Class SlidingWindow

patterns/javascript/slidingWindow.js:1–62  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class SlidingWindow {
2 // Brute Force Approach - O(n * k)
3 findMaxAverageBruteForce(nums, k) {
4 let maxAvg = -Infinity;
5
6 for (let i = 0; i <= nums.length - k; i++) {
7 let sum = 0;
8 for (let j = i; j < i + k; j++) {
9 sum += nums[j];
10 }
11 maxAvg = Math.max(maxAvg, sum / k);
12 }
13 return maxAvg;
14 }
15
16 // Sliding Window Approach - O(n)
17 findMaxAverageSlidingWindow(nums, k) {
18 let sum = nums.slice(0, k).reduce((a, b) => a + b, 0);
19 let maxSum = sum;
20
21 for (let i = k; i < nums.length; i++) {
22 sum += nums[i] - nums[i - k];
23 maxSum = Math.max(maxSum, sum);
24 }
25
26 return maxSum / k;
27 }
28
29 // Sliding Window for Longest Substring Without Repeating Characters
30 lengthOfLongestSubstringSlidingWindow(s) {
31 let seen = new Set();
32 let maxLength = 0, left = 0;
33
34 for (let right = 0; right < s.length; right++) {
35 while (seen.has(s[right])) {
36 seen.delete(s[left]);
37 left++;
38 }
39 seen.add(s[right]);
40 maxLength = Math.max(maxLength, right - left + 1);
41 }
42 return maxLength;
43 }
44
45 // Sliding Window using Frequency Array
46 lengthOfLongestSubstringSlidingWindowFrequencyArray(s) {
47 let freq = new Array(128).fill(0);
48 let maxLength = 0, left = 0;
49
50 for (let right = 0; right < s.length; right++) {
51 freq[s.charCodeAt(right)]++;
52
53 while (freq[s.charCodeAt(right)] > 1) {
54 freq[s.charCodeAt(left)]--;
55 left++;
56 }
57
58 maxLength = Math.max(maxLength, right - left + 1);
59 }
60 return maxLength;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected