"Binary search: find key in list of integers"

This function will take a list of integers and a key as input, and will return the index of the key if it exists in the list, or -1 if it does not exist.


Given a list of integers, write a function that returns the index of the given key if the key exists in the list, or -1 if the key does not exist.
Example input: [1,2,3,4,5], 3
Example output: 2


This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use a for loop to iterate through the array and check if the current element is equal to the key.
// If it is, return the index of the current element. If the loop finishes without finding the key, return -1.
// This solution is optimal because it only iterates through the array once, and therefore has a time complexity of O(n).

function findKey(arr, key) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === key) {
      return i;
  return -1;

console.log(findKey([1, 2, 3, 4, 5], 3)); // 2
console.log(findKey([1, 2, 3, 4, 5], 6)); // -1

A.I. Evaluation of the Solution

This is a good solution that correctly implements a linear search through the array.

Evaluated at: 2022-11-25 12:15:53