š The 18-Day DSA Cover Drive
Learn DSA one Python trick at a time.
What's up, DEV community! š
Welcome to Day 1 of my brand-new coding series.
If you're wondering why it's called The 18-Day DSA Cover Drive, let me let you in on a secret...
I'm a massive Virat Kohli fan. š¤«
Just like a perfect cover drive isn't built in one net session, strong DSA isn't built in one night.
For the next 18 days, I'll share:
- š One Python trick
- š§© One DSA lesson
- ā One mistake I made
- š§ One memory trick to remember it forever
A perfect cover drive isn't born on match day. An optimal solution isn't born during interviews. Both are built in practice.
š Day 1 ā Frequency Count
šÆ Today's Hidden Gem
freq[item] = freq.get(item, 0) + 1
Looks simple.
But this single line can turn an O(n²) solution into an O(n) solution.
š¤ Imagine this...
You walk into your classroom.
The teacher asks,
"How many students are wearing blue?"
ā Method 1
Every time someone asks, you walk around the entire classroom counting students.
Again.
Again.
Again.
Sounds exhausting?
That's exactly what nested loops do.
ā Method 2
Walk through the classroom once and maintain a notebook.
Blue ā 8
Black ā 12
White ā 6
Now every answer takes just a second.
That's the idea behind Frequency Count.
š¬ Movie Memory Trick
Think of Doraemon's Anywhere Door.
Without a dictionary
š¶ Search the whole house.
With a dictionary
šŖ Open the door.
You're already there.
⨠The Magic Line
freq[item] = freq.get(item, 0) + 1
Read it like English.
- Get the current count.
- If it doesn't exist, assume it's 0.
- Add 1.
- Save it back.
Done.
Before
if item in freq:
freq[item] += 1
else:
freq[item] = 1
After
freq[item] = freq.get(item, 0) + 1
ā Cleaner
ā Smaller
ā Easier
š§ Quick Challenge
What will be the output?
arr = [1, 2, 1, 3, 2, 1]
freq = {}
for item in arr:
freq[item] = freq.get(item, 0) + 1
print(freq)
š Put your answer in the comments before running the code!
š Cover Drive of the Day
š Concept: Frequency Count
ā Python Gem: dict.get()
š§ Memory Trick: Classroom Attendance Notebook
āļø Next Innings: defaultdict (Less code. Same logic. Even cleaner.)
18DayDSACoverDrive | Python | DSA | Beginners Learning


Top comments (0)