Arrays are the foundation of many data structure and algorithm problems. Before stacks, queues, heaps, graphs, and dynamic programming feel comfortable, you need to understand how values sit in order and how indexes move through them.
An array is an ordered collection of values. Each value has a position called an index. In most programming languages, indexes start from 0.
index: 0 1 2 3 4 5
value: 14 7 22 9 31 5
The value 14 is at index 0, 7 is at index 1, and 31 is at index 4.
Why arrays matter
Arrays are simple, but they teach the habits used in almost every DSA topic:
- moving through data with an index
- comparing the current value with a target
- updating an answer while scanning
- deciding when to stop early
- reasoning about time and space complexity
Linear search
Linear search checks values one by one until it finds the target or reaches the end.
If the target is 31, the algorithm checks 14, then 7, then 22, then 9, then 31. When it finds the target, it returns index 4.
function linearSearch(values, target) {
for (let index = 0; index < values.length; index++) {
if (values[index] === target) {
return index;
}
}
return -1;
}
Returning -1 is a common convention that means the target was not found.
Complexity
Linear search may need to inspect every item.
- Best case:
O(1)when the first value matches. - Worst case:
O(n)when the target is last or missing. - Space:
O(1)because it only tracks the current index.
Common mistakes
- Starting at index
1and skipping the first item. - Using
index <= values.length, which reads one position beyond the array. - Forgetting to return after finding the target.
- Returning
falsein one solution and-1in another without being consistent.
Practice problems
- Return the index of the first even number.
- Count how many values are greater than
10. - Find the smallest value in an array.
- Return
trueif a target exists, otherwisefalse. - Return all indexes where a target appears.
Practice links
Use the visualizer below to see linear search one step at a time.
Interactive walkthrough
Linear Search Visualizer
Pick a target and step through the array from left to right.