Code Templates

Use these adaptable code templates as starting points for solving hash table problems. Each template includes the core structure with comments explaining the hash table patterns and common variations.

The “Main” Template: Frequency Counter Pattern

This template demonstrates the most common hash table pattern - counting frequencies of elements. It’s the foundation for many other hash table algorithms.

Description: Count occurrences of each element in a collection. This template directly solves problems like Contains Duplicate and Valid Anagram.

/**
 * Template for counting frequencies using Map
 * Use when: Need to count occurrences, find most frequent, validate frequencies
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(k)</div>
</div> where k is unique elements
 */
function frequencyCounter(arr) {
    const freq = new Map();

    // Count frequencies
    for (const item of arr) {
        freq.set(item, (freq.get(item) || 0) + 1);
    }

    // Example usage patterns
    // Find most frequent element
    let maxFreq = 0, mostFrequent = null;
    for (const [item, count] of freq) {
        if (count > maxFreq) {
            maxFreq = count;
            mostFrequent = item;
        }
    }

    // Check for specific frequency
    const targetCount = 2;
    for (const [item, count] of freq) {
        if (count === targetCount) {
            // Found element with target frequency
            return item;
        }
    }

    return freq;
}
"""
Template for counting frequencies using dict
Use when: Need to count occurrences, find most frequent, validate frequencies
Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(k)</div>
</div> where k is unique elements
"""
from collections import defaultdict

def frequency_counter(arr):
    freq = defaultdict(int)

    # Count frequencies
    for item in arr:
        freq[item] += 1

    # Example usage patterns
    # Find most frequent element
    most_frequent = max(freq.items(), key=lambda x: x[1])

    # Check for specific frequency
    target_count = 2
    for item, count in freq.items():
        if count == target_count:
            return item  # Found element with target frequency

    return dict(freq)

# Counter class alternative (built-in)
from collections import Counter

def frequency_counter_builtin(arr):
    freq = Counter(arr)

    # Most common elements
    most_common = freq.most_common(3)  # Top 3 most frequent

    return freq
/**
 * Template for counting frequencies using HashMap
 * Use when: Need to count occurrences, find most frequent, validate frequencies
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(k)</div>
</div> where k is unique elements
 */
import java.util.HashMap;
import java.util.Map;

public class FrequencyCounter {
    public Map<Integer, Integer> countFrequencies(int[] arr) {
        Map<Integer, Integer> freq = new HashMap<>();

        // Count frequencies
        for (int num : arr) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }

        return freq;
    }

    // Find most frequent element
    public int findMostFrequent(int[] arr) {
        Map<Integer, Integer> freq = countFrequencies(arr);
        int maxFreq = 0;
        int mostFrequent = arr[0];

        for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
            if (entry.getValue() > maxFreq) {
                maxFreq = entry.getValue();
                mostFrequent = entry.getKey();
            }
        }

        return mostFrequent;
    }
}
/*
 * Template for counting frequencies using unordered_map
 * Use when: Need to count occurrences, find most frequent, validate frequencies
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(k)</div>
</div> where k is unique elements
 */
#include <unordered_map>
#include <vector>
#include <algorithm>

class FrequencyCounter {
public:
    std::unordered_map<int, int> countFrequencies(const std::vector<int>& arr) {
        std::unordered_map<int, int> freq;

        // Count frequencies
        for (const int& num : arr) {
            freq[num]++;
        }

        return freq;
    }

    // Find most frequent element
    int findMostFrequent(const std::vector<int>& arr) {
        auto freq = countFrequencies(arr);
        int maxFreq = 0;
        int mostFrequent = arr[0];

        for (const auto& entry : freq) {
            if (entry.second > maxFreq) {
                maxFreq = entry.second;
                mostFrequent = entry.first;
            }
        }

        return mostFrequent;
    }
};
/*
 * Template for counting frequencies using map
 * Use when: Need to count occurrences, find most frequent, validate frequencies
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(k)</div>
</div> where k is unique elements
 */
package main

import "fmt"

func frequencyCounter(arr []int) map[int]int {
    freq := make(map[int]int)

    // Count frequencies
    for _, item := range arr {
        freq[item]++
    }

    return freq
}

// Find most frequent element
func findMostFrequent(arr []int) int {
    freq := frequencyCounter(arr)
    maxFreq := 0
    mostFrequent := arr[0]

    for item, count := range freq {
        if count > maxFreq {
            maxFreq = count
            mostFrequent = item
        }
    }

    return mostFrequent
}
# Template for counting frequencies using Hash
# Use when: Need to count occurrences, find most frequent, validate frequencies
# Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(k)</div>
</div> where k is unique elements

def frequency_counter(arr)
    freq = Hash.new(0)

    # Count frequencies
    arr.each do |item|
        freq[item] += 1
    end

    # Example usage patterns
    # Find most frequent element
    most_frequent = freq.max_by { |_, count| count }

    # Check for specific frequency
    target_count = 2
    freq.each do |item, count|
        return item if count == target_count
    end

    freq
end

Code Breakdown

Key Variables

  • freq: The hash table storing element frequencies
  • item: Current element being processed
  • count: Frequency count for each element

Visual Flow

  flowchart TD
    A[Input Array] --> B[Initialize Hash Table]
    B --> C[Process Each Element]
    C --> D[Update Frequency Count]
    D --> E{More Elements?}
    E -->|Yes| C
    E -->|No| F[Return Frequency Map]

Critical Sections

  1. Initialization: Create empty hash table to store frequencies
  2. Frequency Update: Increment count for each element encountered
  3. Lookup: Access existing counts with O(1) average time complexity

Variations

Complement Search Pattern

/**
 * Template for complement-based lookups (two sum pattern)
 * Use when: Finding pairs that sum to target, k-sum variations
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
function complementSearch(nums, target) {
    const seen = new Map();

    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];

        if (seen.has(complement)) {
            // Found pair
            return [seen.get(complement), i];
        }

        seen.set(nums[i], i);
    }

    return []; // No pair found
}
"""
Template for complement-based lookups (two sum pattern)
Use when: Finding pairs that sum to target, k-sum variations
Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
"""

def two_sum(nums, target):
    seen = {}

    for i, num in enumerate(nums):
        complement = target - num

        if complement in seen:
            return [seen[complement], i]

        seen[num] = i

    return []  # No pair found
/**
 * Template for complement-based lookups using HashMap
 * Use when: Finding pairs that sum to target, k-sum variations
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
import java.util.HashMap;
import java.util.Map;

public class ComplementSearch {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> seen = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];

            if (seen.containsKey(complement)) {
                return new int[]{seen.get(complement), i};
            }

            seen.put(nums[i], i);
        }

        return new int[]{}; // No pair found
    }
}
/*
 * Template for complement-based lookups using unordered_map
 * Use when: Finding pairs that sum to target, k-sum variations
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
#include <unordered_map>
#include <vector>

class ComplementSearch {
public:
    std::vector<int> twoSum(const std::vector<int>& nums, int target) {
        std::unordered_map<int, int> seen;

        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];

            if (seen.find(complement) != seen.end()) {
                return {seen[complement], i};
            }

            seen[nums[i]] = i;
        }

        return {}; // No pair found
    }
};
/*
 * Template for complement-based lookups using map
 * Use when: Finding pairs that sum to target, k-sum variations
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
func twoSum(nums []int, target int) []int {
    seen := make(map[int]int)

    for i, num := range nums {
        complement := target - num

        if idx, exists := seen[complement]; exists {
            return []int{idx, i}
        }

        seen[num] = i
    }

    return []int{} // No pair found
}
# Template for complement-based lookups (two sum pattern)
# Use when: Finding pairs that sum to target, k-sum variations
# Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>

def two_sum(nums, target)
    seen = {}

    nums.each_with_index do |num, i|
        complement = target - num

        return [seen[complement], i] if seen.key?(complement)

        seen[num] = i
    end

    [] # No pair found
end

Grouping Pattern

/**
 * Template for grouping elements by property
 * Use when: Grouping anagrams, categorizing by key, building adjacency lists
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
function groupByProperty(arr, keyFunction) {
    const groups = new Map();

    for (const item of arr) {
        const key = keyFunction(item);

        if (!groups.has(key)) {
            groups.set(key, []);
        }

        groups.get(key).push(item);
    }

    return groups;
}

// Example: Group anagrams
function groupAnagrams(strs) {
    return groupByProperty(strs, str => str.split('').sort().join(''));
}
"""
Template for grouping elements by property
Use when: Grouping anagrams, categorizing by key, building adjacency lists
Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
"""
from collections import defaultdict

def group_by_property(arr, key_function):
    groups = defaultdict(list)

    for item in arr:
        key = key_function(item)
        groups[key].append(item)

    return dict(groups)

# Example: Group anagrams
def group_anagrams(strs):
    return group_by_property(strs, lambda s: ''.join(sorted(s)))
/**
 * Template for grouping elements by property
 * Use when: Grouping anagrams, categorizing by key, building adjacency lists
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

public class GroupingPattern {
    public Map<String, List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> groups = new HashMap<>();

        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);

            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
        }

        return groups;
    }
}
/*
 * Template for grouping elements by property
 * Use when: Grouping anagrams, categorizing by key, building adjacency lists
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
#include <unordered_map>
#include <vector>
#include <string>
#include <algorithm>

class GroupingPattern {
public:
    std::unordered_map<std::string, std::vector<std::string>> groupAnagrams(const std::vector<std::string>& strs) {
        std::unordered_map<std::string, std::vector<std::string>> groups;

        for (const auto& str : strs) {
            std::string key = str;
            std::sort(key.begin(), key.end());
            groups[key].push_back(str);
        }

        return groups;
    }
};
/*
 * Template for grouping elements by property
 * Use when: Grouping anagrams, categorizing by key, building adjacency lists
 * Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>
 */
import "sort"

func groupAnagrams(strs []string) map[string][]string {
    groups := make(map[string][]string)

    for _, str := range strs {
        key := sortString(str)
        groups[key] = append(groups[key], str)
    }

    return groups
}

func sortString(s string) string {
    chars := []rune(s)
    sort.Slice(chars, func(i, j int) bool {
        return chars[i] < chars[j]
    })
    return string(chars)
}
# Template for grouping elements by property
# Use when: Grouping anagrams, categorizing by key, building adjacency lists
# Time: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>, Space: <div class="hextra-badge ">
  <div class="hx:inline-flex hx:gap-1 hx:items-center hx:rounded-full hx:px-2.5 hx:leading-6 hx:text-[.65rem] hx:border hx:border-purple-200 hx:bg-purple-100 hx:text-purple-900 hx:dark:border-purple-200/30 hx:dark:bg-purple-900/30 hx:dark:text-purple-200">O(n)</div>
</div>

def group_by_property(arr, key_function)
    groups = Hash.new { |h, k| h[k] = [] }

    arr.each do |item|
        key = key_function.call(item)
        groups[key] << item
    end

    groups
end

# Example: Group anagrams
def group_anagrams(strs)
    group_by_property(strs, ->(str) { str.chars.sort.join })
end

Practice

Ready to apply these templates? Check out our curated problems to practice implementing these patterns in real coding challenges.

Pro Tip: Start with the frequency counter template as it’s the foundation for most hash table problems. Master the complement search pattern for pair-finding problems, and use the grouping pattern when you need to categorize elements by shared properties.