DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

5

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

PROBLEM:
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.
Examples:
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"

EXPLANATION:
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
https://www.php.net/manual/en/function.str-split.php

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: https://www.php.net/manual/en/array.sorting.php)

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

ANSWER:

<?php 
function longest($a, $b) {

$all = $a.$b;

$arr = str_split($all);
sort($arr);

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


return $sortedstring;

}
?>

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

Collapse
 
naveenkolambage profile image
Naveen Dinushka

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️