DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

PHP: Two to one (take 2 strings and return sorted unique string)

Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,
each taken only once - coming from s1 or s2.
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"

In the longest() function we will implement the following;

STEP 1) Combine the two strings
We concatenate (combine two strings in php by the . )

STEP 2) And then convert it into an array

str_split() function lets us pass a string and convert it into an array , here we dont specifiy the second parameter hence it defaults to one

STEP 3) Sort the elements of the array

By just passing an array into the sort() function , it will sort it out we dont need to do this
$arr = sort($arr), infact this is not gonna work ! ( sort($a) passes the value by reference because of that we don't need to assign it to the second variable , learn more:

STEP 4) Convert it into a string while turning the characters in the array into unique characters
$returnstring= implode("",array_unique($arr));

Implode will return a string with the separator specified (first parameters) , here we assign “” (nothing)

STEP 5) Return the string


function longest($a, $b) {

$all = $a.$b;

$arr = str_split($all);

$sortedstring= implode("",array_unique($arr));

return $sortedstring;


Top comments (1)

naveenkolambage profile image
Naveen Dinushka