Sovi.AI - AI Math Tutor

Scan to solve math questions

QUESTION IMAGE

the challenge: write a c++ function that takes two strings, s and t, an…

Question

the challenge:
write a c++ function that takes two strings, s and t, and returns true if t is an anagram of s, and false otherwise. an anagram is a word or phrase formed by rearranging the letters of a different word.

Explanation:

Analyze the requirements for anagram detection

  • Input: Two strings \(s\) and \(t\).
  • Output: Return true if \(t\) is an anagram of \(s\), and false otherwise.
  • Definition: An anagram is formed by rearranging the letters of a different word, meaning both strings must have the exact same character frequencies and length.

Design an efficient algorithm

  • If \(s.\text{length}()

eq t.\text{length}()\), return false.

  • Use a fixed-size frequency array of size 26 (assuming lowercase English letters) or a hash map to count character occurrences.
  • Increment counts for characters in \(s\) and decrement counts for characters in \(t\).
  • If all counts in the frequency array return to 0, the strings are anagrams.

Implement the C++ function

#include <string>
#include <vector>

bool isAnagram(std::string s, std::string t) {
    if (s.length() != t.length()) {
        return false;
    }
    int counts[26] = {0};
    for (int i = 0; i < s.length(); i++) {
        counts[s[i] - 'a']++;
        counts[t[i] - 'a']--;
    }
    for (int count : counts) {
        if (count != 0) {
            return false;
        }
    }
    return true;
}

Answer:

#include <string>

bool isAnagram(std::string s, std::string t) {
    if (s.length() != t.length()) {
        return false;
    }

    int counts[26] = {0};

    for (size_t i = 0; i < s.length(); ++i) {
        counts[s[i] - 'a']++;
        counts[t[i] - 'a']--;
    }

    for (int count : counts) {
        if (count != 0) {
            return false;
        }
    }

    return true;
}