Roadmap › Coding Round Practice (DSA in C#) › Module: Arrays and Hashing
Lessons in this course (14)

6. Two pointers and sliding window

Intermediate★ Must knowLesson 6 of 14
csharp
// Pair with sum in a SORTED array — two pointers O(n)
static bool HasPair(int[] sorted, int target)
{
    int l = 0, r = sorted.Length - 1;
    while (l < r)
    {
        int sum = sorted[l] + sorted[r];
        if (sum == target) return true;
        if (sum < target) l++; else r--;
    }
    return false;
}

// Longest substring without repeating characters — sliding window O(n)
static int LongestUnique(string s)
{
    var last = new Dictionary<char, int>();
    int best = 0, start = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (last.TryGetValue(s[i], out var prev) && prev >= start) start = prev + 1;
        last[s[i]] = i;
        best = Math.Max(best, i - start + 1);
    }
    return best;
}

// Maximum subarray sum — Kadane's algorithm O(n)
static int MaxSubArray(int[] a)
{
    int best = a[0], current = a[0];
    for (int i = 1; i < a.Length; i++)
    {
        current = Math.Max(a[i], current + a[i]);
        best = Math.Max(best, current);
    }
    return best;
}

// Max sum of any window of size k — fixed sliding window
static int MaxWindow(int[] a, int k)
{
    int sum = a.Take(k).Sum(), best = sum;
    for (int i = k; i < a.Length; i++) { sum += a[i] - a[i - k]; best = Math.Max(best, sum); }
    return best;
}