0

Given an array of unique elements = [ 2, 6, 11, 21, 5 ]. How can I write an O(1) algorithm that returns an element that is not the smallest in the array?

//  I tried... but not sure if this is O(1)   -  runtime

$arr = [2, 6, 11, 21, 5];
$smallest = $arr[0];

function returnSmallest() {

   for( i = 1; i < $arr.length; i++ )  
   {
      if($arr[i] < $smallest)
   {
     $smallest = $arr[i];
   }
}  return $smallest;

}();

print($smallest);
15
  • 3
    If you want an element which is not the smallest, just compare the two first elements. O(1) ! Commented Nov 20, 2019 at 16:42
  • 1
    Yes, should return an element that is NOT smallest in the array (correction to the title). I am not sure if my attempt at writing the code /algorithm is correct and represents a runtime of O(1) Commented Nov 20, 2019 at 16:49
  • 1
    @MrCEO, your code is O(n) since you are looping over the entire array, Damien's answer is correct you can just compare first 2 items in array and return the largest ( which btw is O(1) ) Commented Nov 20, 2019 at 16:52
  • 1
    Your code returns the smallest element. It is O(n) as it examines the n elements. Impossible to do better if you want the smallest, as you need to examine all elements in this case. You don't need to examine all elements if you simply want an element which is not the smallest Commented Nov 20, 2019 at 16:52
  • 2
    @MrCEO It's simple when u compare 2 elements and you return the largest, then obviously other element is smaller right? which satisfies your condition "return NOT smallest item in array". let me give as example [10, 4, 3, 11] --> (10 > 4) ---> return(10) which is not the smallest in array. Commented Nov 20, 2019 at 17:03

1 Answer 1

3

Your question is vague. If you want to return the smallest element, there is no O(1) algorithm to do that if you are not storing the elements in a sorted array.

If you want to return an element that is not smallest, your code is wrong, since it is returning the smallest element. You can just return the largest between the first two elements and that is O(1).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.