Introduction
Linear Search is a searching technique used to find a target element in an array by checking each element one by one from the beginning.
Given an array arr[] of size n and a target element x, the task is to determine whether the target element is present in the array.
This is one of the most basic searching algorithms and helps in understanding array traversal, searching techniques, and conditional checking.
Example:
Input: arr[] = [4, 7, 1, 9, 3]Target = 9 Output: Element Found Explanation: 9 is present at index 3.
Input: arr[] = [10, 20, 30, 40] Target = 25 Output: Element Not Found Explanation: 25 is not present in the array.
Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9
-10^9 <= target <= 10^9Approach 1 : Brute Force
Explanation
The simplest way to search for an element is:
- Traverse the array from beginning to end.
- Compare each element with the target value.
- If the element matches:
- return found
- Otherwise continue traversal.
This approach is simple and works for both sorted and unsorted arrays.
Steps
- Traverse the array from index 0.
- Compare each element with the target.
- If target is found:
- return True
- If traversal completes:
- return False
Dry Run
Input Array: [4, 7, 1, 9, 3]Target = 9 Traverse 4: 4 != 9
Continue searching Traverse 7: 7 != 9 Continue searching Traverse 1: 1 != 9 Continue searching Traverse 9: 9 == 9 Target element found
Final Result: Element Found
Brute Force Code
Explanation
The traversal approach itself is the optimal solution for unsorted arrays because elements may appear anywhere in the array.
However, we can optimize slightly using early termination:
- stop traversal immediately once the target element is found.
This avoids unnecessary comparisons.
Steps
- Traverse the array.
- Compare current element with target.
- If target is found:
- immediately stop traversal
- Otherwise continue searching.
- If traversal completes:
- return not found
Dry Run
Input Array: [10, 20, 30, 40]Target = 25 Traverse 10: 10 != 25 Continue searching Traverse 20: 20 != 25
Continue searching Traverse 30: 30 != 25 Continue searching
Traverse 40: 40 != 25 Continue searching Target element not found Final Result: Element Not Found
Optimized Approach
Complexity Analysis
Time Complexity: O(n)Explanation: The array may need to be traversed completely.
Space Complexity: O(1) Explanation: Only constant extra space is used.
Edge Cases