Linear search
Return the first index of a target value in an unsorted integer array, or -1 if it is absent.
Course progress
Problem 19 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [9, 3, 7, 1]; target = 7
Expected output
2
What is happening?
Scanning from the start finds 7 after 9 and 3, at zero-based index 2.
Solution strategy
Build the right mental model
Inspect values from left to right and return as soon as the target is found. If the loop finishes, return -1.
Core concepts
arrays · search
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for linear-search
using System;
class Program
{
static int LinearSearch(int[] numbers, int target)
{
for (int i = 0; i < numbers.Length; i++)
if (numbers[i] == target) return i;
return -1;
}
static void Main()
{
Console.WriteLine(LinearSearch(new[] { 9, 3, 7, 1 }, 7));
}
}Knowledge check
Questions students often ask
What is the main idea behind linear search?
Inspect values from left to right and return as soon as the target is found. If the loop finishes, return -1.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.