## Wednesday, April 19, 2017

### Window Sliding Technique 2

Window Sliding Technique
http://www.geeksforgeeks.org/sum-minimum-maximum-elements-subarrays-size-k/
Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.
Run two loops to generate all subarrays of size k and find maximum and minimum values. Finally return sum of all maximum and minimum elements.
Time taken by this solution is O(nk).
Method 2 (Efficient using Dequeue)
The idea is to use Dequeue data structure and sliding window concept. We create two empty double ended queues of size k (‘S’ , ‘G’) that only store indexes of elements of current window that are not useless. An element is useless if it can not be maximum or minimum of next subarrays.
``` a) In deque 'G', we maintain decreasing order of
values from front to rear
b) In deque 'S', we maintain increasing order of
values from front to rear

1) First window size K
1.1) For deque 'G', if current element is greater
than rear end element, we remove rear while
current is greater.
1.2) For deque 'S', if current element is smaller
than rear end element, we just pop it while
current is smaller.
1.3) insert current element in both deque 'G' 'S'

2) After step 1, front of 'G' contains maximum element
of first window and front of 'S' contains minimum
element of first window. Remaining elements of G
and S may store maximum/minimum for subsequent
windows.

3) After that we do traversal for rest array elements.
3.1) Front element of deque 'G' is greatest and 'S'
is smallest element of previous window
3.2) Remove all elements which are out of this
window [remove element at front of queue ]
3.3) Repeat steps 1.1 , 1.2 ,1.3

4) Return sum of minimum and maximum element of all
sub-array size k.```
`int` `SumOfKsubArray(``int` `arr[] , ``int` `n , ``int` `k)`
`{`
`    ``int` `sum = 0;  ``// Initialize result`
`    ``// The queue will store indexes of useful elements`
`    ``// in every window`
`    ``// In deque 'G' we maintain decreasing order of`
`    ``// values from front to rear`
`    ``// In deque 'S' we  maintain increasing order of`
`    ``// values from front to rear`
`    ``deque< ``int` `> S(k), G(k);`
`    ``// Process first window of size K`
`    ``int` `i = 0;`
`    ``for` `(i = 0; i < k; i++)`
`    ``{`
`        ``// Remove all previous greater elements`
`        ``// that are useless.`
`        ``while` `( (!S.empty()) && arr[S.back()] >= arr[i])`
`            ``S.pop_back(); ``// Remove from rear`
`        ``// Remove all previous smaller that are elements`
`        ``// are useless.`
`        ``while` `( (!G.empty()) && arr[G.back()] <= arr[i])`
`            ``G.pop_back(); ``// Remove from rear`
`        ``// Add current element at rear of both deque`
`        ``G.push_back(i);`
`        ``S.push_back(i);`
`    ``}`
`    ``// Process rest of the Array elements`
`    ``for` `(  ; i < n; i++ )`
`    ``{`
`        ``// Element at the front of the deque 'G' & 'S'`
`        ``// is the largest and smallest`
`        ``// element of previous window respectively`
`        ``sum += arr[S.front()] + arr[G.front()];`
`        ``// Remove all elements which are out of this`
`        ``// window`
`        ``while` `( !S.empty() && S.front() <= i - k)`
`            ``S.pop_front();`
`        ``while` `( !G.empty() && G.front() <= i - k)`
`            ``G.pop_front();`
`        ``// remove all previous greater element that are`
`        ``// useless`
`        ``while` `( (!S.empty()) && arr[S.back()] >= arr[i])`
`            ``S.pop_back(); ``// Remove from rear`
`        ``// remove all previous smaller that are elements`
`        ``// are useless`
`        ``while` `( (!G.empty()) && arr[G.back()] <= arr[i])`
`            ``G.pop_back(); ``// Remove from rear`
`        ``// Add current element at rear of both deque`
`        ``G.push_back(i);`
`        ``S.push_back(i);`
`    ``}`
`    ``// Sum of minimum and maximum element of last window`
`    ``sum += arr[S.front()] + arr[G.front()];`
`    ``return` `sum;`
`}`

http://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
Given two strings string1 and string2, find the smallest substring in string1 containing all characters of string2 efficiently.
```Input :  string = "this is a test string"
pattern = "tist"
Output :  Minimum window is "t stri"
Explanation: "t stri" contains all the characters
of pattern.```
```1- First check if length of string is less than
the length of given pattern, if yes
then "no such window can exist ".
2- Store the occurrence of characters of given
pattern in a hash_pat[].
3- Start matching the characters of pattern with
the characters of string i.e. increment count
if a character matches
4- Check if (count == length of pattern ) this
means a window is found
5- If such window found, try to minimize it by
removing extra characters from beginning of
current window.
6- Update min_length.
7- Print the minimum length window.```
`string findSubString(string str, string pat)`
`{`
`    ``int` `len1 = str.length();`
`    ``int` `len2 = pat.length();`
`    ``// check if string's length is less than pattern's`
`    ``// length. If yes then no such window can exist`
`    ``if` `(len1 < len2)`
`    ``{`
`        ``cout << ``"No such window exists"``;`
`        ``return` `""``;`
`    ``}`
`    ``int` `hash_pat[no_of_chars] = {0};`
`    ``int` `hash_str[no_of_chars] = {0};`
`    ``// store occurrence ofs characters of pattern`
`    ``for` `(``int` `i = 0; i < len2; i++)`
`        ``hash_pat[pat[i]]++;`
`    ``int` `start = 0, start_index = -1, min_len = INT_MAX;`
`    ``// start traversing the string`
`    ``int` `count = 0;  ``// count of characters`
`    ``for` `(``int` `j = 0; j < len1 ; j++)`
`    ``{`
`        ``// count occurrence of characters of string`
`        ``hash_str[str[j]]++;`
`        ``// If string's char matches with pattern's char`
`        ``// then increment count`
`        ``if` `(hash_pat[str[j]] != 0 &&`
`            ``hash_str[str[j]] <= hash_pat[str[j]] )`
`            ``count++;`
`        ``// if all the characters are matched`
`        ``if` `(count == len2)`
`        ``{`
`            ``// Try to minimize the window i.e., check if`
`            ``// any character is occurring more no. of times`
`            ``// than its occurrence  in pattern, if yes`
`            ``// then remove it from starting and also remove`
`            ``// the useless characters.`
`            ``while` `( hash_str[str[start]] > hash_pat[str[start]]`
`                   ``|| hash_pat[str[start]] == 0)`
`            ``{`
`                ``if` `(hash_str[str[start]] > hash_pat[str[start]])`
`                    ``hash_str[str[start]]--;`
`                ``start++;`
`            ``}`
`            ``// update window size`
`            ``int` `len_window = j - start + 1;`
`            ``if` `(min_len > len_window)`
`            ``{`
`                ``min_len = len_window;`
`                ``start_index = start;`
`            ``}`
`        ``}`
`    ``}`
`    ``// If no window found`
`    ``if` `(start_index == -1)`
`    ``{`
`       ``cout << ``"No such window exists"``;`
`       ``return` `""``;`
`    ``}`
`    ``// Return substring starting from start_index`
`    ``// and length min_len`
`    ``return` `str.substr(start_index, min_len);`
`}`