Valid Anagram β Complete LeetCode Solution with Hash Map Pattern
Let BliniBot prep you for interviews
Try BliniBot FreeThe Valid Anagram problem is one of the most frequently tested coding interview questions and a perfect example of the Hash Map pattern. Understanding this problem deeply will help you recognize and solve dozens of related problems that share the same underlying algorithmic structure. In this guide, we provide a complete walkthrough of the solution in both Python and TypeScript, explain the time and space complexity, discuss common variations, and show you how to recognize when to apply the Hash Map pattern in new problems. Whether you are preparing for interviews at Google, Amazon, Meta, or any top tech company, mastering this fundamental pattern is essential. We start with the brute force approach to build intuition, then optimize step by step to arrive at the optimal solution. Each step is explained with the reasoning behind it so you can reproduce this thinking process in an actual interview rather than relying on memorization. The Hash Map pattern appears in approximately 15 to 20 percent of all coding interview questions, making it one of the highest-leverage patterns to study thoroughly.
Problem Statement and Examples
Count character frequencies in the first string, then decrement for each character in the second. If any count goes negative or lengths differ, they are not anagrams. Space is O(1) since the alphabet is fixed. This problem is classified as Easy difficulty, though the Hash Map technique it requires appears in problems across all difficulty levels. Understanding the core mechanic here unlocks solutions to many harder problems. Let us first examine what makes this problem well-suited for the Hash Map approach: we need to process elements in a way that avoids redundant computation, and the Hash Map pattern gives us exactly that efficiency. The brute force approach would check all possible combinations, resulting in O(n squared) or worse time complexity. The Hash Map optimization reduces this dramatically by maintaining state intelligently as we traverse the input. Before coding, always verify your understanding by working through small examples by hand β this catches misunderstandings early and demonstrates thoroughness to your interviewer.
Python Solution
Here is the optimal Python solution using the Hash Map pattern. Python's clean syntax makes the algorithm's logic easy to follow. Pay attention to how we initialize our data structures and handle edge cases before entering the main loop. The variable naming reflects the algorithmic concept to make the code self-documenting. In an interview, writing clean and readable code like this signals professionalism and attention to detail. Let us walk through the code line by line and understand why each decision was made.
def is_anagram(s, t):
if len(s) != len(t):
return False
count = {}
for c in s:
count[c] = count.get(c, 0) + 1
for c in t:
count[c] = count.get(c, 0) - 1
if count[c] < 0:
return False
return TrueTypeScript Solution
The TypeScript implementation uses the same algorithmic approach with proper type annotations. TypeScript's type system helps catch errors at compile time and makes the code more maintainable. Notice how the generic types and interfaces document the expected input and output formats. If your target company uses TypeScript (which is increasingly common in 2026), demonstrating fluency in typed solutions gives you an edge. The logic mirrors the Python solution exactly, so understanding one helps you write the other quickly.
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const count: Record<string, number> = {};
for (const c of s) count[c] = (count[c] || 0) + 1;
for (const c of t) {
count[c] = (count[c] || 0) - 1;
if (count[c] < 0) return false;
}
return true;
}Have a question about Valid Anagram β Complete LeetCode Solution with Hash Map Pattern?
Ask BliniBot βComplexity Analysis
Time complexity: O(n). Space complexity: O(1). Understanding complexity analysis is critical because interviewers almost always ask about it, and incorrect analysis can cost you the problem even if your code is correct. For time complexity, count how many times each element is processed β in the Hash Map pattern, each element is typically visited a constant number of times, giving us linear time. For space complexity, consider the auxiliary data structures used beyond the input and output. In this solution, the space usage is O(1) because we only use a constant number of variables regardless of input size. When comparing approaches, an algorithm that is O(n) time and O(n) space is generally preferred over O(n log n) the and O(1) the for most interview contexts, since the complexity is usually the primary optimization target.
Ready to automate? BliniBot connects to 200+ tools.
Start Free TrialWhen to Use the Hash Map Pattern
The Hash Map pattern is applicable when you see these characteristics in a problem: the input involves a linear data structure (array, string, or linked list), you need to find or optimize something among contiguous or related elements, and a brute force approach would involve nested loops. Common signal words include "subarray," "substring," "consecutive," "contiguous," "minimum/maximum window," and "pair." Practice recognizing these signals across different problem phrasings. The Hash Map pattern also combines well with other techniques: you might use Hash Map as the outer strategy and binary search or hash maps as inner tools. Building this pattern recognition through deliberate practice is more effective than solving hundreds of random problems. Focus on understanding why the pattern works, not just how to apply it mechanically.
- Look for problems involving contiguous elements or subsequences in arrays and strings
- Check if brute force would require nested iteration that the Hash Map can eliminate
- Consider whether maintaining running state eliminates recomputation
- Practice converting brute force to Hash Map solutions to build intuition for the optimization step
Common Variations and Follow-ups
Interviewers frequently modify this problem to test deeper understanding. Common variations include: changing the constraint (find all pairs vs first pair, minimum vs maximum), modifying the input format (sorted vs unsorted, with duplicates vs without), adding constraints (in-place modification, space limit), or extending to higher dimensions (2D matrix version). For each variation, the core Hash Map technique remains but the implementation details change. Practice at least 3 to 4 variations of every core problem to build the flexibility needed for interview success. When you encounter a variation in an interview, explicitly state how it differs from the base problem and how that difference affects your approach β this demonstrates depth of understanding that impresses interviewers. The Valid Anagram problem also frequently appears as a subproblem within harder questions, so understanding it thoroughly provides building blocks for tackling complex problems.
Key Takeaways
- 1.The Valid Anagram problem is best solved using the Hash Map pattern with O(n) time complexity
- 2.Always start with brute force to build intuition before optimizing to the Hash Map approach
- 3.Practice recognizing signal words that indicate when the Hash Map pattern applies
- 4.Master both Python and TypeScript implementations since companies test in different languages
- 5.Understand complexity analysis deeply β interviewers expect you to justify your Big-O claims
Frequently Asked Questions
What is the optimal time complexity for Valid Anagram?
The optimal solution runs in O(n) time and O(1) space. The Hash Map technique achieves this by processing each element a constant number of times, avoiding the nested iteration that a brute force approach would require. Any solution faster than this would need to skip elements, which risks missing the correct answer for this problem. In an interview, state the complexity clearly and be prepared to prove it by tracing through the algorithm with a sample input.
How do I recognize Hash Map problems in interviews?
Look for these patterns: the problem involves a linear data structure, you need to find an optimal substructure or pair, and brute force would require quadratic time. Signal words include contiguous, subarray, substring, pair, window, and consecutive. The Hash Map pattern is one of the most versatile techniques, appearing in approximately 15 to 20 percent of coding interviews. Practice identifying these signals in problem statements before reading the solution to build your pattern recognition ability.
Should I memorize the solution to Valid Anagram?
No. Memorization fails in interviews because interviewers modify problems to test understanding, not recall. Instead, understand why the Hash Map approach works for this problem structure. Learn the pattern, practice applying it to multiple problems, and build the ability to derive solutions from first principles. If you understand the underlying mechanics, you can handle any variation the interviewer throws at you, which is exactly what they are testing.
What if I get stuck on Valid Anagram during an interview?
Start with the brute force approach and explain it clearly. Then analyze what makes it slow (usually redundant computation in nested loops). Ask yourself: what information from the previous iteration can I reuse? This naturally leads to the Hash Map optimization. Communicate your thought process throughout β interviewers give credit for systematic problem-solving even if you do not reach the optimal solution immediately. Asking good clarifying questions and testing with examples also buys thinking time.
Related Articles
Research companies and their tech stacks before your next interview. Analyze top companies β
NexusBro helps developers catch bugs and SEO issues before they reach production. Try it free β
Automate your workflow with AI
14-day free trial. No charge today. Cancel anytime.
Start Free TrialReady to automate?
Join thousands of teams using BliniBot to automate repetitive tasks. Start free, upgrade anytime.