20. Check if an Array Contains a Given Element

Difficulty:EasyPattern:Linear Search / Boolean SearchTime:O(n)Space:O(1)

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:

  1. Traverse the array from left to right.
  2. Compare every value with the target.
  3. Return true immediately when a match is found.
  4. 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=12
The target exists in the array.
Search: 5 -> 8 -> 12
The search stops as soon as 12 is found.
Output: true
The 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).