20. Check if an Array Contains a Given Element
Given an array and a target value, determine whether the target exists in the array.
How It Works & Algorithmic Design
Use a basic linear search:
- Traverse the array from left to right.
- Compare every value with the target.
- Return
trueimmediately when a match is found. - If the loop completes without finding the target, return
false.
Why This Approach Works Best
For an unsorted array, there is no information that allows us to skip arbitrary positions. Linear search provides $O(n)$ worst-case time and $O(1)$ auxiliary space.
Example Walkthrough
Input:
[5, 8, 12, 3, 20], Target=12The target exists in the array.
Search:
5 -> 8 -> 12The search stops as soon as 12 is found.
Output:
trueThe target exists at index 2.
Answer: Check whether target exists
function contains(arr, target) {
for (const value of arr) {
if (value === target) return true;
}
return false;
}💡 Use linear search and return immediately when the target is found.
Key Takeaways
- Linear search can answer existence questions directly.
- Early return avoids unnecessary comparisons when the target is found.
- Worst-case time is O(n), while auxiliary space is O(1).