Efficient Anagram Detection in PHP: A Simple Approach

Athira Radhakrishnan
2 min readMar 28, 2024

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

  1. 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.
  2. 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 :)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Athira Radhakrishnan
Athira Radhakrishnan

Written by Athira Radhakrishnan

Systems Engineer | PHP | SQL | Magento | Aspiring Cybersecurity Student | Professionally active since 2021 | GitHub : https://github.com/AthiraBR

No responses yet

Write a response