Course outline · 0% complete

0/29 lessons0%

Course overview →

Frequency maps and two pointers

lesson 10-2 · ~6 min · 28/29

Two patterns that solve half the easy problems

Interview problems repeat themselves: behind fresh wording, a small set of patterns does most of the work, and recognizing one turns a blank stare into a plan. This lesson drills the two highest-frequency patterns for strings and arrays — each replaces a naive O(n²) nested loop with an O(n) or O(n log n) idea, which is usually the exact improvement the interviewer is waiting for you to name.

Frequency map (lesson 7-2's counting idiom): count occurrences first, then answer questions in a second pass. First non-repeating character, anagram checks, and most "count the..." problems fall to it.

Anagram check: two words are anagrams if sorting their characters gives the same result.

char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
Arrays.sort(a);
Arrays.sort(b);
boolean anagram = Arrays.equals(a, b);

toCharArray() explodes a String into a char array, and java.util.Arrays provides sort, equals, and toString for arrays. These three static helpers appear in nearly every interview solution you will write.

Code exercise · java

Run both patterns: the frequency map finds the first character of swiss that appears exactly once, and the sort-and-compare check confirms listen and silent are anagrams.

Two pointers

Many array and string tasks compare or move elements from both ends: reverse in place, check a palindrome without building a copy, find a pair in sorted data. The two-pointer pattern keeps one index at each end and walks them toward each other:

int left = 0;
int right = arr.length - 1;
while (left < right) {
  // work with arr[left] and arr[right]: swap, compare...
  left++;
  right--;
}

Each element is visited once, so the whole pass is O(n) with no extra array — the two things this pattern is prized for. The loop condition left < right is the standard stop: the pointers have met or crossed, meaning every pair has been handled.

123456leftrightswap, then left++ and right--, stop when they meet
The two-pointer pattern: one index walks in from each end. Each step does its work (swap, compare) and moves the pointers toward each other.

Code exercise · java

Your turn. Reverse the array in place with two pointers: while left < right, swap the elements, then move both pointers inward. Print the result with Arrays.toString.