NeetCode 150 / Two Pointers
HardTwo PointersO(n)
ভিডিওতে দেখো — YouTube @algonur_com

কোড

Python
def trap(height: list[int]) -> int:
    l, r = 0, len(height) - 1
    maxL, maxR = height[l], height[r]
    water = 0
    while l < r:
        if maxL <= maxR:
            l += 1
            maxL = max(maxL, height[l])
            water += maxL - height[l]
        else:
            r -= 1
            maxR = max(maxR, height[r])
            water += maxR - height[r]
    return water
Java
public int trap(int[] h) {
    int l=0, r=h.length-1, maxL=h[0], maxR=h[h.length-1], water=0;
    while (l < r) {
        if (maxL <= maxR) { l++; maxL=Math.max(maxL,h[l]); water+=maxL-h[l]; }
        else { r--; maxR=Math.max(maxR,h[r]); water+=maxR-h[r]; }
    }
    return water;
}
Kotlin
fun trap(height: IntArray): Int {
    var l=0; var r=height.size-1; var maxL=height[l]; var maxR=height[r]; var water=0
    while(l<r) {
        if(maxL<=maxR){l++;maxL=maxOf(maxL,height[l]);water+=maxL-height[l]}
        else{r--;maxR=maxOf(maxR,height[r]);water+=maxR-height[r]}
    }
    return water
}
C++
int trap(vector<int>& h) {
    int l=0,r=h.size()-1,maxL=h[0],maxR=h.back(),water=0;
    while(l<r){
        if(maxL<=maxR){l++;maxL=max(maxL,h[l]);water+=maxL-h[l];}
        else{r--;maxR=max(maxR,h[r]);water+=maxR-h[r];}
    }
    return water;
}
C
int trap(int* h, int n) {
    int l=0,r=n-1,maxL=h[0],maxR=h[n-1],water=0;
    while(l<r){
        if(maxL<=maxR){l++;maxL=maxL>h[l]?maxL:h[l];water+=maxL-h[l];}
        else{r--;maxR=maxR>h[r]?maxR:h[r];water+=maxR-h[r];}
    }
    return water;
}

জটিলতা

O(n)
সময় — অ্যারেটা একবারই ঘুরি, ম্যাপে খোঁজা O(1)।
O(1)
জায়গা — সবচেয়ে খারাপ ক্ষেত্রে সব সংখ্যা ম্যাপে থাকে।
আগের সমস্যা← Container With Most Waterপরের সমস্যাBest Time to Buy and Sell Stock →