Data Structures & Algorithms·Reason about cost and structure

Arrays, strings and two pointers

Contiguous storage is fast; index discipline is everything.

Intermediate 14 min read Lesson 7 of 300 Challenge included
What you will be able to do
  • Prefer linear scans when the data is already ordered.
  • Use two pointers for sorted pair and window problems.
  • Be explicit about whether indexes are inclusive or exclusive.

In plain English

Arrays give O(1) indexed access and O(n) insertion in the middle. Two-pointer techniques turn some nested scans into a single pass. Strings are sequences with their own encoding and immutability rules.

two-pointers.jsJavaScript
function hasPairSum(sorted, target) {
  let left = 0
  let right = sorted.length - 1

  while (left < right) {
    const sum = sorted[left] + sorted[right]
    if (sum === target) return true
    if (sum < target) left += 1
    else right -= 1
  }
  return false
}
Your turn

Reverse in place

Medium

Reverse an array of characters in place using two pointers.

JS · starter
function reverse(chars) {}
Check your understanding before moving on.
Knowledge checkQuestion 1

Why does the two-pointer pair-sum algorithm rely on sorted input?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Stacks and queues
Lesson 7 of 300 · 0% of course