Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions solutions/0201-0300/0242-valid-anagram/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# 242. Valid Anagram

[LeetCode problem 242](https://leetcode.com/problems/valid-anagram/)

- **Difficulty**: Easy
- **Tags**: hash-table, string, sorting

## Description

Given two strings `s` and `t`, return `true` if `t` is an anagram of `s`
(uses the exact same letters, same counts), `false` otherwise.
44 changes: 44 additions & 0 deletions solutions/0201-0300/0242-valid-anagram/solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include "solution.hpp"

#include <algorithm>
#include <array>
#include <unordered_map>

namespace leetcode::p0242 {

bool solve(const std::string& s, const std::string& t) {
if (s.size() != t.size()) {
return false;
}

std::array<int, 26> counts{};

for (char c : s) {
++counts.at(static_cast<std::size_t>(c - 'a'));
}
for (char c : t) {
--counts.at(static_cast<std::size_t>(c - 'a'));
}

return std::ranges::all_of(counts, [](int count) { return count == 0; });
}

bool solveHashMap(const std::string& s, const std::string& t) {
if (s.size() != t.size()) {
return false;
}

std::unordered_map<char, int> countS;
std::unordered_map<char, int> countT;

for (char c : s) {
++countS[c];
}
for (char c : t) {
++countT[c];
}

return countS == countT;
}

} // namespace leetcode::p0242
15 changes: 15 additions & 0 deletions solutions/0201-0300/0242-valid-anagram/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#pragma once

#include <string>

namespace leetcode::p0242 {

// optimized: O(n) time, O(1) space — fixed 26-slot count array (assumes
// lowercase English letters, per the problem's constraints).
bool solve(const std::string& s, const std::string& t);

// hash-map: O(n) time, O(k) space (k = distinct characters) — works for any
// character set, not just lowercase English letters.
bool solveHashMap(const std::string& s, const std::string& t);

} // namespace leetcode::p0242
13 changes: 13 additions & 0 deletions solutions/0201-0300/0242-valid-anagram/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#include <catch2/catch_test_macros.hpp>

#include "solution.hpp"

TEST_CASE("Problem 242 - optimized", "[p0242]") {
CHECK(leetcode::p0242::solve("anagram", "nagaram"));
CHECK_FALSE(leetcode::p0242::solve("rat", "car"));
}

TEST_CASE("Problem 242 - hash map", "[p0242]") {
CHECK(leetcode::p0242::solveHashMap("anagram", "nagaram"));
CHECK_FALSE(leetcode::p0242::solveHashMap("rat", "car"));
}
20 changes: 0 additions & 20 deletions swift/242.swift

This file was deleted.

Loading