Algorithm LogbookAlgorithm Logbook

Linear Search

Month 1Week 1Day 3

๐Ÿ“‹ Problem Statement

Given an array arr[] and an integer target, return the index of the target element. If the target is not found in the array, return -1. The array is not necessarily sorted.

๐Ÿ’ก Intuition

Linear search is the most fundamental searching algorithm. Since we have no information about the ordering of elements, we must check every element one by one. The key insight is that this is the best we can do for an unsorted array โ€” there is no shortcut.

๐Ÿ”ง Approach

1. Iterate through the array using enumerate to get both the index and value. 2. At each position, compare the current element with the target. 3. If they match, immediately return the current index. 4. If the loop completes without finding the target, return -1.

โšก Complexity Analysis

Time
O(N) where N is the length of the array โ€” in the worst case, we check every element
Space
O(1) โ€” no extra space is used beyond loop variables

โš ๏ธ Common Mistakes

- Returning 0 instead of -1 when the element is not found (0 is a valid index) - Not handling empty arrays (the loop simply doesn't execute and returns -1 correctly) - Forgetting to return immediately when the element is found, causing unnecessary iterations

๐ŸŽฏ Final Thoughts

Linear search is simple but important to understand. It establishes the baseline complexity for searching: O(N). Later, you will learn Binary Search which achieves O(log N) โ€” but only works on sorted arrays. Understanding this trade-off is fundamental to choosing the right algorithm.