Optimizing Python Data Structures: When to Use deque, defaultdict, and Counter

Deque

from collections import deque

def sliding_window_max(nums, k):
dq = deque() # Stores indices
result = []

for i, num in enumerate(nums):
# Remove elements not in sliding window
if dq and dq[0] < i – k + 1:
dq.popleft()

# Remove smaller elements (they won’t be needed)
while dq and nums[dq[-1]] < num:
dq.pop()

dq.append(i)

# Append max of current window
if i >= k – 1:
result.append(nums[dq[0]])

return result

# Example
nums = [1,3,-1,-3,5,3,6,7]
k = 3
print(sliding_window_max(nums, k)) # [3, 3, 5, 5, 6, 7]

Default dict

from collections import defaultdict

data = [(“Alice”, “Math”), (“Bob”, “Science”), (“Alice”, “Physics”)]

grouped = defaultdict(list)

for name, subject in data:
grouped[name].append(subject)

print(grouped)
# {‘Alice’: [‘Math’, ‘Physics’], ‘Bob’: [‘Science’]}

Counter

from collections import Counter

words = [“apple”, “banana”, “apple”, “orange”, “banana”, “banana”]
word_freq = Counter(words)

print(word_freq)
# Counter({‘banana’: 3, ‘apple’: 2, ‘orange’: 1})

from collections import Counter

letters = “abracadabra”
letter_freq = Counter(letters)

print(letter_freq.most_common(2))
# [(‘a’, 5), (‘b’, 2)]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top