Back to Home

Patterns Two Pointers HashMap Stack for interviews

The article breaks down Two Pointers, HashMap and Stack patterns with JavaScript code examples. Each pattern is illustrated with a problem, algorithm and application checklist. Suitable for technical interview preparation.

3 patterns for 60% of problems at JS interview
Advertisement 728x90

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.

Google AdInline article slot
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.

Google AdInline article slot
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:

Google AdInline article slot

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

Advertisement 728x90

Read Next