MemPro
ExploreSign in
Coding Interview Problems, Vol. 1Medium

Medium

15 cards
  • Card 1 / 15

    Group Anagrams

    Given a list of words strs, group the words that are anagrams of one another (the same letters in a different order). Return the groups as a list of lists. To make the answer unique: sort each group ascending, then sort the groups by their first word. An empty input gives an empty list.

    strs result why
    ["eat", "tea", "tan", "ate", "nat", "bat"] [["ate", "eat", "tea"], ["bat"], ["nat", "tan"]] groups ordered ate < bat < nat
    ["abc", "xyz", "bca", "abc"] [["abc", "abc", "bca"], ["xyz"]] duplicates stay in one group
    [""] [[""]] the empty word is its own group
    [] []

    Two words are anagrams exactly when they have the same canonical key. Two common keys: the word's letters sorted ("eat" → "aet", costs O(klog⁡k)O(k \log k)O(klogk) per word of length kkk), or a count of each of the 26 letters ("eat" → 26 counts, O(k)O(k)O(k), and the count tuple/array is itself the key). Put each word into a hash map keyed that way; every bucket is one group. Finish by sorting inside each bucket and sorting the buckets by their first word so the output is deterministic.

    Python
    def group_anagrams(strs):
        """Group the words that are anagrams of each other (same letters, any order).
        Return a list of groups: each group sorted ascending, and the groups sorted
        by their first word."""
        groups = {}  # sorted-letters key -> words made of exactly those letters
        for word in strs:
            key = "".join(sorted(word))
            groups.setdefault(key, []).append(word)
        # Fix the output order so it is deterministic: inside each group, then by first word.
        result = [sorted(group) for group in groups.values()]
        result.sort(key=lambda group: group[0])
        return result
  • Card 2 / 15

    Longest Substring Without Repeating Characters

    Given a string s, return the length of its longest substring (contiguous run of characters) in which no character appears twice. The empty string gives 0.

    Subscribe to learn