Three Essential Patterns for Coding Interview Algorithms
The Two Pointers pattern uses two pointers to scan data in a single pass. It drops complexity from O(n²) to O(n) for palindromes, element pairs, and filtering tasks.
Two main variations:
- Left-Right (converging): left starts at index 0, right at s.length - 1. Move them toward the center for symmetry checks.
- Slow-Fast: slow updates the result, fast scans ahead for removing duplicates or shifting elements.
Example: checking a palindrome ignoring non-alphabetic characters.
const isPalindrome = (s) => {
let left = 0;
let right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) {
return false;
}
left++;
right--;
}
return true;
};
console.log(isPalindrome("madam")); // true
console.log(isPalindrome("abc")); // false
HashMap: Fast Lookups and Grouping
HashMap (object or Map) stores key-value pairs for O(1) access. Perfect for frequency counts, uniqueness checks, anagrams, and caching.
Algorithm: one pass to build, second to query. Skips nested loops entirely.
Example: first unique character in a string.
const firstUniqueChar = (s) => {
const map = {};
for (const char of s) {
map[char] = (map[char] || 0) + 1;
}
for (const char of s) {
if (map[char] === 1) {
return char;
}
}
return null;
};
console.log(firstUniqueChar("banana")); // 'b'
console.log(firstUniqueChar("aabbc")); // 'c'
Stack: Handling LIFO Structures
Stack follows Last In - First Out. An array with push/pop shines for bracket validation, recursion-free stacks, and backtracking.
Example: validating bracket sequences.
const isValidBrackets = (s) => {
const stack = [];
const map = {
')': '(',
']': '[',
'}': '{'
};
for (const char of s) {
if ('([{'.includes(char)) {
stack.push(char);
} else {
const last = stack.pop();
if (last !== map[char]) {
return false;
}
}
}
return stack.length === 0;
};
console.log(isValidBrackets("{[()()]}")); // true
console.log(isValidBrackets("{[(])}")); // false
When to Use Each Pattern
Before coding, spot these cues:
Two Pointers:
- Array/string with symmetry (palindrome).
- Finding element pairs.
- Sorted array.
- Comparing from both ends.
HashMap:
- Counting frequencies or uniqueness.
- Anagrams, grouping.
- Checking element existence.
- Unsorted data needing fast lookups.
Stack:
- Brackets or nested structures.
- LIFO logic (last opened closes first).
- Backtracking or state history.
Key Takeaways
- Two Pointers saves data passes, perfect for linear structures.
- HashMap delivers O(1) access, swapping nested loops for two passes.
- Stack ensures proper nesting order without recursion.
- Practice: solve 10 problems per pattern, then mix them.
These patterns tackle most LeetCode/Codewars Easy/Medium problems. Regular use builds senior-level interview intuition.
— Editorial Team
No comments yet.