DEV Community

Ertugrul
Ertugrul

Posted on • Edited on

πŸ—“ Daily LeetCode Progress – Day 2

Problems Solved:

  • #242 Valid Anagram
  • #49 Group Anagrams

This is a follow‑up to my daily series (Day 1: Two Sum & Contains Duplicate). Today I focused on string hashing/sorting patterns and pushed both Python and C++ solutions.


πŸ’‘ What I Learned

Today, I focused on practicing string manipulation and hashing techniques in both Python and C++.

Key takeaways:

  • Python: Learned how to leverage sorted() and defaultdict for concise grouping of anagrams.
  • C++: Reinforced understanding of unordered_map for hashing and the trade-off between sorting vs. counting keys for efficiency.
  • Realized that mutating containers while iterating (in Python) or mishandling return types (in C++) are common pitfalls to watch out for.

🧩 #242 β€” Valid Anagram

Python (Sorting)

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        new_s = ''.join(sorted(s))
        new_t = ''.join(sorted(t))
        return new_s == new_t
Enter fullscreen mode Exit fullscreen mode

Why it works: anagrams have identical sorted representations.

Time: O(k log k) per string.
Space: O(k) due to intermediate copies.

C++ (Sorting)

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};
Enter fullscreen mode Exit fullscreen mode

Alternative (when alphabet is known, e.g., lowercase a–z): count array of size 26 β†’ O(k).


🧩 #49 β€” Group Anagrams

Python (Sorted Key)

from collections import defaultdict

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)
        for word in strs:
            key = ''.join(sorted(word))  # canonical form
            groups[key].append(word)
        return list(groups.values())
Enter fullscreen mode Exit fullscreen mode

Time: O(n Β· k log k)
Space: O(n Β· k)

C++ (Sorted Key)

#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> groups;
        groups.reserve(strs.size());
        for (string word : strs) {
            string key = word;
            sort(key.begin(), key.end());
            groups[key].push_back(move(word));
        }
        vector<vector<string>> result;
        result.reserve(groups.size());
        for (auto &kv : groups) {
            result.push_back(move(kv.second));
        }
        return result;
    }
};
Enter fullscreen mode Exit fullscreen mode

Bonus: O(n Β· k) Counting‑Key (idea)

  • Build a frequency vector of 26 counts for each word and use it (as a tuple or joined string) as the map key.
  • Avoids sorting cost β†’ better for long strings.

Pseudo‑key example (C++ idea): key = "#c0#c1#c2...#c25" from the 26 counters.


πŸ“Έ Achievements

  • Valid Anagram (Python & C++):

VA python

VA cpp

  • Group Anagrams (Python & C++):

GA python

GA c++


πŸ“¦ Complexity Recap

  • Valid Anagram: O(k log k) (sort) or O(k) (counts)
  • Group Anagrams: O(n Β· k log k) (sort key) or O(n Β· k) (count key)

πŸ“£ Join the Journey

I’m posting daily, solving each task in both Python and C++, and writing down what actually matters (patterns, mistakes, and trade‑offs). Follow along if you’re into algorithms and practical performance.

Links

Top comments (0)