For the problem Leetcode problem here, here’s my solution in PHP. Most examples found are Python and so much shorter using Sets.
The question itself has not target space or time complexity and my question is if there is a more efficient PHP solution.
class Solution {
/**
* @param String[] $strs
* @return String[][]
*/
function groupAnagrams($strs) {
$result = [];
$alreadyPlaced = [];
$currentPalindromes = [];
$hashed = [];
foreach($strs as $key => $str) {
// create assoc array mapping letter to index of str its from
if ( array_key_exists($key, $alreadyPlaced) ) continue;
// mark this as placed
$alreadyPlaced[$key] = true;
// initiatilize new array and place into new array
$currentPalindromes = array();
array_push($currentPalindromes, $str);
// to be able to determine palindromes, hash each letter in the newly found string
$hashed = array();
foreach (str_split($str) as $c) {
$hashed[$c] = true;
}
//loop thru all strings skipping those of not same length or already accounted for
foreach($strs as $checkKey => $checkVal) {
$breakout = false;
if (mb_strlen($checkVal) != mb_strlen($str)) continue;
if (array_key_exists($checkKey, $alreadyPlaced)) continue;
foreach (str_split($checkVal) as $c) {
if (!$hashed[$c]) {
$breakout = true;
continue;
}
}
if ($breakout) continue;
// if it got here, its a palindrome
array_push($currentPalindromes, $checkVal);
$alreadyPlaced[$checkKey] = true;
}
//add new palindrome array into $result array
array_push($result, $currentPalindromes);
}
return $result;
}
2
Answers
You have way too much code here. You start well, but overcomplicate the process of grouping the anagrams. Here’s my solution:
This simplifies the process by sorting the characters in each source string. Each anagram of a given word will generate the same sorted list, which makes it easy to compare anagrams.
Use that sorted anagram as an index into an associative array, and add the original word to an array at that index. If the anagram hasn’t been seen a new entry is created. If it has, the word is added to the output array.
Finally, return only the values from the associative array to meet the requirements of the challenge.
The solution is accepted for both run time and memory.
sort()
since thesort()
itself isO(N Log N)
, which makes the total running timeO(N x N x Log N)
:Results: