Master advanced hash table techniques and learn how to solve complex problems efficiently using hash-based data structures.
Track occurrences of elements in arrays, strings, or streams of data.
Store frequently accessed data for quick retrieval.
Efficiently remove or identify duplicate items.
Data Structure | Main Features | When to Use | Performance |
---|---|---|---|
Object |
|
Simple key-value mapping with string keys | Average O(1) for access, insertion, deletion |
Map |
|
When key order matters or when using non-string keys | Average O(1) for access, insertion, deletion |
Set |
|
When you need to track unique values without associated keys | Average O(1) for access, insertion, deletion |
WeakMap / WeakSet |
|
When tracking object references that should be garbage collected | Average O(1) for access, insertion, deletion |
def count_frequency(arr):
frequency_map = {}
for item in arr:
frequency_map[item] = frequency_map.get(item, 0) + 1
return frequency_map
# Example: Count letter frequency
letters = "programming"
print(count_frequency(letters))
def first_non_repeating_char(s):
# Create frequency map
char_count = {}
# First pass: count frequencies
for char in s:
char_count[char] = char_count.get(char, 0) + 1
# Second pass: find first char with count 1
for char in s:
if char_count[char] == 1:
return char
return None
def first_non_repeating_char(s):
# Create frequency map
char_count = {}
# First pass: count frequencies
for char in s:
char_count[char] = char_count.get(char, 0) + 1
# Second pass: find first char with count 1
for char in s:
if char_count[char] == 1:
return char
return None
print(first_non_repeating_char("leetcode")) # "l"
print(first_non_repeating_char("aabbcc")) # None
print(first_non_repeating_char("aabbc")) # "c"
def first_non_repeating_char_optimized(s):
char_info = {}
# Single pass: track both count and first position
for i, char in enumerate(s):
if char not in char_info:
char_info[char] = {'count': 1, 'first_index': i}
else:
char_info[char]['count'] += 1
# Find character with count 1 and minimum index
result = None
min_index = len(s)
for char, info in char_info.items():
if info['count'] == 1 and info['first_index'] < min_index:
result = char
min_index = info['first_index']
return result
Implement a function that finds the first character that repeats in a string.
firstRepeatingChar("abcdeef") → "e"
firstRepeatingChar("abcde") → null
firstRepeatingChar("abba") → "b"
Create a function that returns a map of character frequencies in descending order.
charFrequency("programming") →
{
"g": 2,
"r": 2,
"m": 2,
"p": 1,
"o": 1,
"a": 1,
"i": 1,
"n": 1
}
Write a function that groups anagrams together from an array of strings.
groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) →
[
["eat", "tea", "ate"],
["tan", "nat"],
["bat"]
]