Two Pointer and sliding window pattern
Two-pointer and sliding window patterns
Pattern 1: Constant window(Like window = 4 or some Integer value)
For example given an array of (-ve and +ve) integers find the max sum for the contiguous window of size k.
Pattern 2:(Variable window size) Largest subarray/substring with
- Approaches:
- Brute Force: Generate all possible subarrays and choose the max length subarray with sum <=k (this will have time complexity of $O(n^2)$.
- Betten/Optimal: Make use of two pointer and sliding window to reduce the time complexity to O(n)
Pattern 3: No of subarray/substring where
This is very difficult to solve because it becomes difficult when to expand (right++) or when to shrink(left++).
This problem can be solved using Pattern 2
For solving problems like finding the number of substrings where sum =k.
-
This can be broken down to
- Find subarrays where sum<=k ----X
- Find subarray where sum<=k-1----Y then the result will be X-Y = answer
Pattern 4: Find the shortest/minimum window
Different approaches for pattern 2:
Example: Largest subarray with sum<=k
public class Sample{ public static void main(String args[]){ n = 10; int arr[] = new int[n]; //Brute force approach for finding the longest subarray with sum <=k //tc : O(n^2) int maxlen=0; for(int i =0;i<arr.length;i++){ int sum =0; for(int j = i+1;j<arr.length;j++){ sum+=arr[j]; if(sum<=k){ maxLen = Integer.max(maxLen, j-i+1); } else if(sum > k) break; /// optimization if the sum is greater than the k, what is the point in going forward? } } <p><strong>Better approach using the two pointers and the sliding window</strong><br> </p> <pre class="brush:php;toolbar:false"> //O(n+n) in the worst case r will move from 0 to n and in the worst case left will move from 0 0 n as well so 2n int left = 0; int right =0; int sum = 0; int maxLen = 0; while(right<arr.length){ sum+=arr[right]; while(sum > k){ sum = sum-arr[left]; left++; } if(sum <=k){ maxLen = Integer.max(maxLen, right-left+1); //if asked to print max subarray length,we print maxLen else asked for printing the subarray keep track of // left and right in a different variable } right++; }
Optimal approach:
We know that if we find the subarray we store its length in maxLen, but while adding arr[right] if the sum becomes more than the k then currently we are shrinking left by doing sum = sum-arr[left] and doing left++.
We know that the current Max length is maxLen, if we keep on shrinking the left index we might get another subarray satisfying the condition (<=k) but the length might be less than the current maxLen then we will not update the maxLen till we find another subarray satisfying the condition and also having len > maxLen, then only maxLen will be updated.
An optimal approach will be to only shrink the left as long as the subarray length is more than the maxLen when the subarray is not satisfying the condition (<=k)int left = 0.
int right =0; int sum = 0; int maxLen = 0; while(rightk){// this will ensure that the left is incremented one by one (not till the sum<=k because this might reduce the length i.e right-left+1 which will not be taken into consideration) sum = sum-arr[left]; left++; } if(sum <=k){ maxLen = Integer.max(maxLen, right-left+1); //if asked to print max subarray length,we print maxLen else asked for printing the subarray keep track of // left and right in a different variable } right++; } } } The above is the detailed content of Two Pointer and sliding window pattern. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...
