DSA interview question
A small library app keeps its book IDs in the order they were added, not sorted, and a librarian types an ID to check whether the book exists and where it sits in the list. Without sorted data or an index there's only one option: look at each element in turn until you find it or run out. Linear search is the baseline every other search is measured against, and knowing exactly when it's the right tool (unsorted data, a single query, tiny arrays) is as important as knowing the faster alternatives.
Example: [10, 20, 30, 40], target 30 → index 2.
int linearSearch(const vector<int>& a, int target); // index of the first occurrence, or -1
Input (a, target) | Output | Explanation |
|---|---|---|
([10, 20, 30, 40], 30) | 2 | |
([5, 3, 5], 5) | 0 | First occurrence |
([1, 2, 3], 4) | -1 | Not present |
([7], 7) | 0 | |
([], 1) | -1 | Empty array |
([4, -2, 9, -2], -2) | 1 | Negative values |
(Confirm: return the index of the first occurrence, or -1 if the target is absent; the array is not sorted.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in