Skip to main content

Linear Search in Array

Problem Statement:​

  • Example:



int linearSearch(const vector<int>& arr, int target) {
for (int i = 0; i < arr.size(); i++) {
if (arr[i] == target) {
return i; // Return index where target is found
}
}
return -1; // Target not found
}


📝 How It Works​

  • Traverse the array from left to right using a loop.
  • At each step, check if the current element is equal to the target.
  • If a match is found, return its index immediately.
  • If the loop completes without a match, return 1 to indicate "not found".

🧩 Key Formula / Recurrence​

  • No recurrence or DP involved.

  • Core condition:

    if (arr[i] == target) → return i;


⏱️ Time & Space Complexity​

CaseTime ComplexitySpace Complexity
Best CaseO(1)O(1)
Average CaseO(N)O(1)
Worst CaseO(N)O(1)
  • Best case: target is at index 0.
  • Worst case: target is at the end or not present.

⚠️ Edge Cases​

  • Empty array → always return 1.
  • All elements same but not equal to target → return 1.
  • Multiple occurrences → returns first match only.
  • Array contains negative and positive integers → works without modification.

💡 Other Approaches​

ApproachTimeSpaceNotes
Binary SearchO(log N)O(1)Only works on sorted arrays
Hashing (map)O(1) avgO(N)Fast lookup but uses space

  • Binary Search (when array is sorted)
  • Search Insert Position
  • First Occurrence of Element
  • Find Element in Rotated Sorted Array

🚀 Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚡
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

💡Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→