MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Hash Map Patterns: Two Sum, Frequency Counters & Subarray Sums0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
4.1Stacks: LIFO Operations, Array/List Implementations & Bracket Matching4.2Monotonic Stacks: Next Greater Element & Histogram Area Patterns4.3Queues: FIFO Mechanics, Circular Buffers & Double-Ended Queues (Deque)4.4Hash Tables: Hash Functions, Separate Chaining & Open Addressing4.5Hash Map Patterns: Two Sum, Frequency Counters & Subarray Sums
HomeTutorialsData Structures & AlgorithmsHash Map Patterns: Two Sum, Frequency Counters & Subarray Sums
Recursion Fundamentals: Base Cases, Recursive Leaps & Call Stack Visuals

Hash Map Patterns: Two Sum, Frequency Counters & Subarray Sums

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Hash maps are the single most effective tool for transforming sluggish brute-force $O(n^2)$ solutions into $O(n)$ linear time. By caching values in memory for instant $O(1)$ lookup, hash map patterns conquer interview classics: Frequency Counters, Unsorted Two Sum, and Subarray Sum Equals K.


1. Real-World Analogy: The Detective's Suspect Board

Imagine a detective looking for two puzzle pieces that combine to equal a target clue:

  • Brute Force: Pick Piece 1, compare it against all other 10,000 pieces. Repeat for Piece 2, Piece 3 ($10,000^2$ comparisons).
  • Hash Map Look-Back Pattern:
  • When inspecting Piece $X$, calculate what piece you need: $\text{Complement} = \text{Target} - X$.
  • Check your detective notebook (Hash Map): "Have I already seen the Complement?"
  • If yes, you found the pair instantly! If no, write $X$ in your notebook and move to the next piece.

2. Pattern 1: Unsorted Two Sum ($O(n)$ Time, $O(n)$ Space)

Given an unsorted array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Python 3 Implementation:

1def two_sum(nums: list[int], target: int) -> list[int]:
2 seen = {} # Maps value -> index
3
4 for i, num in enumerate(nums):
5 complement = target - num
6 if complement in seen:
7 return [seen[complement], i]
8 seen[num] = i
9
10 return []

Modern JavaScript / TypeScript:

1export function twoSum(nums: number[], target: number): number[] {
2 const seen = new Map<number, number>(); // value -> index
3 
4 for (let i = 0; i < nums.length; i++) {
5 const complement = target - nums[i];
6 if (seen.has(complement)) {
7 return [seen.get(complement)!, i];
8 }
9 seen.set(nums[i], i);
10 }
11 
12 return [];
13}

3. Pattern 2: Frequency Counters & Valid Anagrams

Determine if string t is an anagram of string s (contains the exact same characters with identical counts):

1def is_anagram(s: str, t: str) -> bool:
2 if len(s) != len(t):
3 return False
4
5 counts = {}
6 for char in s:
7 counts[char] = counts.get(char, 0) + 1
8
9 for char in t:
10 if char not in counts or counts[char] == 0:
11 return False
12 counts[char] -= 1
13
14 return True

4. Pattern 3: Subarray Sum Equals K (Prefix Sum + Hash Map)

Find the total number of continuous subarrays whose sum equals k:

  • As we maintain a running prefix sum curr_sum, we need to know how many previous prefix sums equaled curr_sum - k.
  • Storing prefix sum frequencies in a Hash Map unlocks an $O(n)$ solution for negative and positive numbers alike!
1def subarray_sum_equals_k(nums: list[int], k: int) -> int:
2 prefix_counts = {0: 1} # Base case: a prefix sum of 0 has occurred once
3 curr_sum = 0
4 total_subarrays = 0
5
6 for num in nums:
7 curr_sum += num
8 # If (curr_sum - k) exists in map, we found valid subarrays!
9 if (curr_sum - k) in prefix_counts:
10 total_subarrays += prefix_counts[curr_sum - k]
11
12 prefix_counts[curr_sum] = prefix_counts.get(curr_sum, 0) + 1
13
14 return total_subarrays

5. Trace Table: Two Sum on nums = [2, 11, 7, 15], target = 9

Index ($i$)nums[i]complement = 9 - nums[i]In seen Map?Actionseen Map State
027NoStore {2: 0}{2: 0}
111-2NoStore {11: 1}{2: 0, 11: 1}
272Yes! (index 0)Return [0, 2]Pair Found!

Result: Returned [0, 2] in a single pass of 3 steps!


Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
How does using a Hash Map reduce the Two Sum problem from $O(n^2)$ to $O(n)$?
Question 2
In the "Subarray Sum Equals K" problem, why must the prefix sum map be initialized with {0: 1}?
Question 3
What is the time complexity of verifying if two strings of length $n$ are anagrams using a Frequency Counter hash table?
Question 4
What is the space-time tradeoff of the Hash Map Two Sum approach compared to the Two-Pointer approach on an unsorted array?
Question 5
Why should you avoid using plain JavaScript objects ({}) as hash maps when keys are arbitrary objects or when prototype pollution is a security risk?

Next Lesson

Recursion Fundamentals: Base Cases, Recursive Leaps & Call Stack Visuals

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Hash Tables: Hash Functions, Separate Chaining & Open AddressingRecursion Fundamentals: Base Cases, Recursive Leaps & Call Stack Visuals

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext