JS Built-ins
Algorithmsbeginner

Linear Search

πŸ“– Usage Example
function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++)
    if (arr[i] === target) return i;
  return -1;
}
linearSearch([3, 1, 4, 1, 5], 4); // 2

Linear search checks every element in order β€” O(n) time, works on unsorted arrays.

Linear Search

Linear search (also called sequential search) is the simplest search algorithm. It iterates through the array from the first element until it finds the target value or reaches the end.

Time Complexity: O(n) Space Complexity: O(1)

function linearSearch(arr: number[], target: number): number {
  // Find the index of target in arr
  // Return -1 if not found
}

linearSearch([10, 20, 30, 40, 50], 30) // 2
linearSearch([10, 20, 30], 99) // -1
πŸ’‘ Hints (4)
  • β€’ Loop through each element starting at index 0.
  • β€’ Compare each element with the target.
  • β€’ Return the index immediately when found.
  • β€’ Return -1 if the loop completes without finding it.