[1] Algorithm Showdown: Python vs. JavaScript – Group Anagrams



This content originally appeared on DEV Community and was authored by Anushadevi Rajkumar

I’ve been revisiting data structures and algorithms lately, but I with a twist to my brain this time: I’m tackling each problem in two different languages to see how they compare. 👾

Welcome to the first post in this series, where I solve the same coding problem in both Python and JavaScript – and discuss about what stands out in each.

[LC-49] Group Anagrams

Problem

Given an array of strings, group all anagrams together. Anagrams are words formed by rearranging letters of another word.

Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

🐍 Python Approach

from collections import defaultdict

def group_anagrams(strs):
    result = defaultdict(list)

    for s in strs:
        # Count character frequency
        count = [0] * 26
        for char in s:
            count[ord(char) - ord('a')] += 1

        # Use tuple as hash key
        key = tuple(count)
        result[key].append(s)

    return list(result.values())

Python learnings: 🖊

  • defaultdict(list) eliminates key existence checks
  • tuple(count) is naturally hashable

🟨 JavaScript Approach

function groupAnagrams(strs) {
    const result = new Map();

    for (let s of strs) {
        // Count character frequency
        const count = new Array(26).fill(0);
        for (let char of s) {
            count[char.charCodeAt(0) - 'a'.charCodeAt(0)]++;
        }

        // Convert array to string for hashing
        const key = count.join(',');

        if (!result.has(key)) {
            result.set(key, []);
        }
        result.get(key).push(s);
    }

    return Array.from(result.values());
}

JavaScript learnings: 🖊

  • Manual key existence validation is required
  • Array needs string conversion for Map keys

📊 Key Takeaways

Python JavaScript
Hash Key tuple(count) count.join(',')
Default Values defaultdict Manual checks

Performance: Both are O(n×m) time, O(n×m) space

Comment with the quirks or features you find most distinctive in Python and JavaScript. Or your take on this DSA problem!


This content originally appeared on DEV Community and was authored by Anushadevi Rajkumar