-
-
Save harmlessprince/25f6bf8b23557c9582a02500043545c6 to your computer and use it in GitHub Desktop.
<?php | |
function FindStartEnd($array, $val) | |
{ | |
$type = gettype($array); | |
try { | |
if (!$array) { | |
throw new Exception("Expects parameter 1 to be array and should contain at least one value"); | |
} | |
if (!is_numeric($val)) { | |
throw new Exception("Second value passed must be a number"); | |
} | |
if(sort($array)){ | |
$indexes = array_keys($array, $val); | |
if (!$indexes) { | |
return [-1, -1]; | |
} | |
return [min($indexes), max($indexes)]; | |
} | |
throw new Exception("expects parameter 1 to be array, $type given"); | |
} catch (Exception $e) { | |
echo 'Error: ' . $e->getMessage() . "\n"; | |
} | |
} | |
print_r(FindStartEnd([0,8,-2,5,0], 0)); |
This is a more optimal solution with improved time complexity because like you rightly mentioned, adding the sorting made the time complexity O(N log N)
.
At this point, the performance of your solution is now dependent on the implementation of the array_keys
function. Do you know that works?
It is like a syntax sugar for a for loop that iterates to the given array and returns all the keys.
But when you give it a value, then only the keys with the specified value are returned.
That is what I know
Really commendable effort @harmlessprince, I like this solution a lot better even though it is still dependent on the performance of array_keys
and count
functions.
I have written a blog post here sharing my solution to this problem - a solution that avoids having to sort the array. Please read through and let me know what you think.
Thank you for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.
Thank you very much and look forward to coming Friday.
By the way, the link is broken, I am getting a 404 error.
Here is another solution considering our previous discussions