Efficient Anagram Detection in PHP: A Simple Approach

Anagrams, which are words or phrases formed by rearranging the letters of another word or phrase, present an interesting problem in programming.
Introduction
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Exploring the Code
Let’s delve into the PHP class Solution
and its method isAnagram($s, $t)
:
class Solution {
/**
* @param String $s
* @param String $t
* @return Boolean
*/
function isAnagram($s, $t) {
if(strlen($s) != strlen($t)) {
return false;
}
$countS = array_count_values( str_split($s)) ;
$countT= array_count_values(str_split($t)) ;
return $countS == $countT;
}
}
How It Works
- Length Check: The function checks if the lengths of the two input strings s and t are equal. If they are not, it immediately returns
false
, as strings with different lengths cannot be anagrams of each other. - Counting Characters:
- It uses
str_split()
to split each input string into an array of characters. array_count_values()
is then used to count the occurrences of each character in both arrays.
3. Comparison: The function compares the counts of characters in both arrays. If the counts are equal, it returns true
, indicating that the strings are anagrams. Otherwise, it returns false
.
Time and Space Complexity
Time Complexity: O(n) where n is the length of the longer string between s and t.
Space Complexity: O(n) where n is the number of unique characters in the input strings s and t.
Conclusion
The provided PHP solution efficiently determines whether two strings are anagrams by comparing the frequencies of characters.
Happy Coding :)