Skip to content

Map & Set Patterns

PatternUse CaseExample
Frequency counterCount occurrences of elementsCharacter frequency in a string
Index lookupStore element→index mappingsTwo Sum problem
Pair problemsFind complement pairsPair with given sum
Caching / MemoizationCache computed resultsFibonacci memoization
GroupingGroup elements by propertyGroup anagrams
PatternUse CaseExample
Remove duplicatesFilter unique valuesRemove duplicates from array
Membership checkCheck if element existsContains duplicate
Uniqueness problemsEnsure all elements are uniqueLongest substring without repeats
Cycle detectionDetect cycles in linked listsLinked list cycle detection
Intersection / DifferenceSet operationsIntersection of two arrays
FeatureMapObject
Key typesAny type (objects, functions, primitives)Only strings and symbols
OrderInsertion order preservedInteger keys ordered, others insertion order
Size.size propertyManual tracking needed
PerformanceOptimized for frequent add/deleteGood for static data
IterationDirectly iterable (for...of)Need Object.keys() or Object.entries()
PrototypeNo prototype chainHas inherited properties
// Map — use for dynamic data
const map = new Map();
map.set('key', 'value');
map.get('key'); // 'value'
map.has('key'); // true
map.delete('key'); // Remove
map.size; // Get size
// Object — use for static data / JSON
const obj = { key: 'value' };
obj.key; // 'value'
'key' in obj; // true
Object.keys(obj); // ['key']
function characterFrequency(str) {
const freq = new Map();
for (const ch of str) {
freq.set(ch, (freq.get(ch) || 0) + 1);
}
return freq;
}
// 'hello' → {'h':1, 'e':1, 'l':2, 'o':1}
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [-1, -1];
}
// [2, 7, 11, 15], target=9 → [0, 1]
function containsDuplicate(nums) {
const set = new Set(nums);
return set.size !== nums.length;
}
// [1,2,3,1] → true (1 appears twice)
function intersection(nums1, nums2) {
const set1 = new Set(nums1);
const result = new Set();
for (const num of nums2) {
if (set1.has(num)) {
result.add(num);
}
}
return [...result];
}
// [1,2,2,1], [2,2] → [2]
function firstUniqueChar(s) {
const freq = new Map();
for (const ch of s) {
freq.set(ch, (freq.get(ch) || 0) + 1);
}
for (let i = 0; i < s.length; i++) {
if (freq.get(s[i]) === 1) return i;
}
return -1;
}
// 'leetcode' → 0 ('l' is first unique)

Next: Two Pointer Technique →