codekofi
← All questions

Valid Anagram

HardArrays & Hashing

The problem

Given two strings, return true if the second is a rearrangement of the first — the same characters with the same multiplicities, in any order.

isAnagram("anagram", "nagaram")

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1bool isAnagram(const string& s, const string& t) {
2
3 if (s.size() == t.size()) {
4 return false;
5 }
6
7 unordered_map<char, int> tally;
8
9 for (char c : s) {
10 tally[c]++;
11 }
12
13 for (char c : t) {
14
15 tally[c - 1]--;
16
17 if (tally[c] < 0) {
18 return false;
19 }
20 }
21
22 return true;
23}
1bool isAnagram(const string& s, const string& t) {
2
3 if (s.size() == t.size()) {
4 return false;
5 }
6
7 unordered_map<char, int> tally;
8
9 for (char c : s) {
10 tally[c]++;
11 }
12
13 for (char c : t) {
14
15 tally[c]--;
16
17 if (tally[c - 1] < 0) {
18 return false;
19 }
20 }
21
22 return true;
23}
1bool isAnagram(const string& s, const string& t) {
2
3 if (s.size() != t.size()) {
4 return false;
5 }
6
7 unordered_map<char, int> tally;
8
9 for (char c : s) {
10 tally[c]++;
11 }
12
13 for (char c : t) {
14
15 tally[c]--;
16
17 if (tally[c] < 0) {
18 return false;
19 }
20 }
21
22 return true;
23}