R
Rishtaara
Data Structures & Algorithms
Lesson 2 of 8Article20 minFREE

Arrays and Strings Patterns

Arrays and Strings Patterns

Core patterns

  • Two pointers for sorted data and pair problems.
  • Sliding window for contiguous subarray/substring constraints.
  • Frequency map for counting characters and duplicates.
  • Prefix sums for fast range sum queries.

Sliding window example

Longest substring without repeating characters
function longestUniqueSubstring(s: string): number {
  const lastSeen = new Map<string, number>();
  let left = 0;
  let best = 0;

  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    if (lastSeen.has(ch) && (lastSeen.get(ch) ?? -1) >= left) {
      left = (lastSeen.get(ch) ?? 0) + 1;
    }
    lastSeen.set(ch, right);
    best = Math.max(best, right - left + 1);
  }

  return best;
}