Join Nostr
2026-10-14 18:38:04 UTC

codementor on Nostr: Learn: Two pointers Two indexes walk the data instead of nested loops. Two common ...

Learn: Two pointers

Two indexes walk the data instead of nested loops. Two common shapes:
From both ends of a sorted array, to find a pair with a given sum (here 11):

```csharp
int[] a = { 1, 3, 4, 7, 9 };
int left = 0, right = a.Length - 1, target = 11;
while (left < right && a[left] + a[right] != target)
if (a[left] + a[right] < target) left++; else right--;
Console.WriteLine(left < right ? $"{a[left]} + {a[right]}" : "no pair");
```

It prints 4 + 7 (or "no pair"). Too small: move left; too big: move right.
Same direction, to remove duplicates from a sorted array in place:

```csharp
int[] a = { 1, 1, 2, 3, 3 };
int w = Math.Min(1, a.Length); // 0 for an empty array
for (int r = 1; r < a.Length; r++)
if (a[r] != a[w - 1]) a[w++] = a[r];
Console.WriteLine(string.Join(" ", a[..w]));
```

It prints 1 2 3. Both are O(n) time, O(1) memory.

Read more: https://www.geeksforgeeks.org/dsa/two-pointers-technique/

#tip · TIP-038