Friday, February 17, 2023

Coding Challenge #5

Daily Coding Problem #4


Given an array of integers, find the missing lowest-value positive integer. The array is not organized by value.
The integers in the array can be either negative or positive, and the array can contain duplicates as well.
Examples: [3, 4, -1, 1] => 2 is the answer (only 1+ can be the answer, the soonest number not in the array is it)
[1,2,0] => 3
[-100, 1, 2, 97] => 3
This was listed as hard, but it seems super easy; hopefully I understood the problem correctly.
To give a little more substance to this post, let's give a solution in a few languages:

// JavaScript
function get(ary){
    var lowest = 1;
    for(var xint = 0, len = ary.length;xint < len;xint++){
        if(ary[xint] == lowest){
            lowest++;
            xint = -1; // restart loop, to check for number that's 1 higher than new lowest
        }
    }
    return lowest;
}

// PHP
function get($ary){
    $lowest = 1;
    for($xint = 0, $len = sizeof($ary);$xint < $len;$xint++){
        if($ary[$xint] == $lowest){
            $lowest++;
            $xint = -1;
        }
    }
    return $lowest;
}

# Python
def get(ary):
    lowest = 1
    for ia in range(len(ary)): # can't manipulate loop index in py, so nest a loop
        for ib in ary[ia:]:
            if ib == lowest:
                lowest += 1
    return lowest

// C++
int get(int* ary, int len){
    int lowest = 1;
    for(int xint = 0;xint < len;xint++){
        if(ary[xint] == lowest){
            lowest++;
            xint = -1;
        }
    }
    return lowest;
}

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...