DEV Community

Preethii V
Preethii V

Posted on

The 18-Day DSA Cover Drive: Day 1 — Unleashing the Frequency Map šŸ

šŸ 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. 🤫

Virat Kohli

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

virat kohli

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

After

freq[item] = freq.get(item, 0) + 1
Enter fullscreen mode Exit fullscreen mode

āœ… 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)
Enter fullscreen mode Exit fullscreen mode

šŸ‘‡ 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)