DSA Basics: Arrays and Linear Search

A beginner-friendly DSA tutorial that explains arrays, indexes, linear search, complexity, mistakes, and practice problems.

Back to Learn DSA

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:

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.

Common mistakes

Practice problems

  1. Return the index of the first even number.
  2. Count how many values are greater than 10.
  3. Find the smallest value in an array.
  4. Return true if a target exists, otherwise false.
  5. Return all indexes where a target appears.

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.

Index 0 14
Index 1 7
Index 2 22
Index 3 9
Index 4 31
Index 5 5
Index 6 18