Some Coding Puzzle Exercises For Fun - Part 2 - Find Non-Recurring Letters

Sat, 02/10/2018 - 18:50

This project was "a little" bit more difficult than the last project...but, not much. I have a feeling this could be done more efficiently however, I am not entirely sure how...I'll revisit this some other time. 

In this project the solution comes from finding the first occurrence in the code not of a recurrence but, instead a non-occurrence. So whereas in the previous version we could find say 'A' for example then another 'A' somewhere else in the set the jump out and be done with it. For this project (at least as far as I can tell so far) we have to continue all the way to the end of the set to make sure there are no more occurrences. This does not mean however, that it's not possible to find multiple occurrences of a single letter.

In this version we are still looking for recurrence of a string but unlike the previous version we need to count the recurrence instead of simply acknowledging that a recurrence exists. That being said in order to save space it makes sense to only count when a recurrence has happened more than once.

I could also further optimize the code by using a boolean instead of an increment but I am not sure how much benefit there might be in managed code.

Finally we loop the final result and this time if the result is equal to one we can jump out of the loop and be done with the whole thing.


// find non-recurring letters in a set

$s = 'aaaaabbbssssdddyyyeejjjiiidyyyeeeoookyyyssrrqqqzmmmddppp';
$result = first_nonrecurring($s);

if(false === $result) {
    echo "No results found";
    echo $result;

echo "\n";

 * first_recurring
 * @param string
 * @return variant
 * */
function first_nonrecurring($s) {
    // init an array
    $f = [];
    // get the length of the test set
    $l = strlen($s);
    for($i=0; $i<$l; $i++) {
        $c = substr($s,$i,1);
        // its ONLY necessary in this exercise to get the first non-recurrence
        // so the found array only needs to increment by one...this could actually just be a boolean really
        // in un-managed code or say MYSQL an this would make a difference
        // in MYSQL for example an int by default is 11 whereas a tinyint (if declared as such) is only a 1
        // BUT...I digress
        if(isset($f[$c])) {
            $f[$c] = 2;
            $f[$c] = 1;
    // this COULD be long...but it will still probably be relatively small
    // maybe a better method could be done using an associative array 
    foreach($f as $k => $v) {
        if($v==1)return $k;
    return false;