← Hash MapDSA 1.3.B

Frequency Counting

Single frequency map, decrement-and-check-zero pattern. Ransom Note, Valid Anagram.

StatusCollected
Notes2 solved

One frequency map, built from one collection and drained by the other — Ransom Note and Valid Anagram both reduce to this exact shape.

int canConstruct(char *ransomNote, char *magazine) {
      int freq[26] = {0};
      for (int i = 0; magazine[i]; i++) freq[magazine[i] - 'a']++;

      for (int i = 0; ransomNote[i]; i++) {
          int idx = ransomNote[i] - 'a';
          if (freq[idx] == 0) return 0;   /* check before decrementing */
          freq[idx]--;
      }
      return 1;
  }

One map is enough — building a second frequency map for the ransom note itself and comparing the two is extra work a single decrement-as-you-go pass avoids entirely. Checking == 0 before decrementing is what catches a letter that's already exhausted; skip that check and the count just goes negative, quietly signaling "has enough" when it doesn't. For Valid Anagram specifically, checking the two string lengths match first is worth doing before touching a hash map at all — it's a free early exit that also removes the need for a third comparison pass afterward.

Notes from readers

Comments — via GitHub