DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Pattern: sliding window (Variable window)

Sliding window of variable size that satisfy given constraint, i.e
Finding continuous substring/subarray that satisfies the given condition.
e.g. Longest substring without repeating characters

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int l = 0;
        int r = 0;
        int size = 0;
        int arr[]  = new int[256];
        Arrays.fill(arr,-1); //intially indices of all the characters are -1

        while(r<s.length()){
            char c = s.charAt(r);
            if(arr[c]!=-1){ //seen in the past
                if(arr[c] >=l){ // if it was seen after the left index then we have a duplicate in the range of l and r we have to move the left pointer
                    l = arr[c]+1; 
                }

            }
            arr[c] = r;
            size= Math.max(size, r-l+1);
            r++;
        }
        return size;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)