1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Linear Search
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
14Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Linear Search

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
14Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Linear Search

Overview

Linear Search is the simplest and most intuitive searching algorithm. To find a specific element in an array or list, you simply start at the beginning (index 0) and check every single element one by one until you find the target, or until you reach the end of the collection.

Because it checks every element sequentially, it does not require the data to be sorted. This makes it highly versatile. It works on unsorted arrays, Linked Lists, and any data structure that allows sequential iteration.

However, its simplicity is its weakness. In the worst-case scenario (the target is the very last element, or doesn't exist at all), you must check every single item. For a collection of 10 million items, that means 10 million checks. Therefore, its time complexity is strictly O(N).

Syntax

Basic Linear Search
java
public class LinearSearch {
    // Returns the index of the target, or -1 if not found
    public static int search(int[] arr, int target) {
        // Iterate through the entire array
        for (int i = 0; i < arr.length; i++) {
            // Check if current element matches the target
            if (arr[i] == target) {
                return i; // Found it! Return the index.
            }
        }
        
        // If the loop finishes without returning, it's not here
        return -1;
    }
    
    public static void main(String[] args) {
        int[] data = {45, 12, 89, 33, 7};
        
        int index = search(data, 33);
        System.out.println("Found at index: " + index); // Output: 3
    }
}

Common Pitfalls

  • Using Linear Search on massive datasets when the data is already sorted. If you know the array is sorted, using a Linear Search is a massive waste of processing power. You should always use Binary Search (O(log N)) for sorted data.
  • Returning boolean false instead of -1 when searching for indices. A common beginner mistake is mixing up search functions that return the existence of an item (boolean) with functions that return the location of an item (integer). If returning an index, always use -1 to represent 'not found', as 0 is a valid index.
  • Comparing Objects using == instead of .equals(). If your array contains Strings or custom objects, if (arr[i] == target) will check for memory reference equality, not value equality. This will fail silently. Always use if (arr[i].equals(target)) for objects.

Interview Questions

What is the Best Case, Worst Case, and Average Case time complexity for Linear Search?

Best Case: O(1) if the target is the very first element. Worst Case: O(N) if the target is the very last element or not in the array. Average Case: O(N/2), which mathematically simplifies to O(N).

Can Linear Search be used on a Singly Linked List?

Yes, absolutely. Since a Linked List only supports sequential access anyway, traversing from head to tail node-by-node is the only way to search it. The time complexity remains O(N).

Real-World Example

When a teacher scans a messy, unalphabetized stack of test papers looking for 'John Doe', they are performing a physical linear search. They must check every paper one by one. In software, searching a small, unsorted configuration file for a specific key-value pair uses linear search.

example
java
public String findConfigValue(List<ConfigOption> config, String targetKey) {
    // The config list is small and unsorted
    for (ConfigOption option : config) {
        if (option.key.equals(targetKey)) {
            return option.value;
        }
    }
    return "DEFAULT_VALUE";
}

Check Your Knowledge

Test your understanding of Linear Search with these quick questions.

Question 1

Does Linear Search require the array to be sorted beforehand?

Question 2

What is the worst-case time complexity of Linear Search?

Question 3

Why do we typically return `-1` if the item is not found in an array?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Linear Search

Overview

Linear Search is the simplest and most intuitive searching algorithm. To find a specific element in an array or list, you simply start at the beginning (index 0) and check every single element one by one until you find the target, or until you reach the end of the collection.

Because it checks every element sequentially, it does not require the data to be sorted. This makes it highly versatile. It works on unsorted arrays, Linked Lists, and any data structure that allows sequential iteration.

However, its simplicity is its weakness. In the worst-case scenario (the target is the very last element, or doesn't exist at all), you must check every single item. For a collection of 10 million items, that means 10 million checks. Therefore, its time complexity is strictly O(N).

Syntax

Basic Linear Search
java
public class LinearSearch {
    // Returns the index of the target, or -1 if not found
    public static int search(int[] arr, int target) {
        // Iterate through the entire array
        for (int i = 0; i < arr.length; i++) {
            // Check if current element matches the target
            if (arr[i] == target) {
                return i; // Found it! Return the index.
            }
        }
        
        // If the loop finishes without returning, it's not here
        return -1;
    }
    
    public static void main(String[] args) {
        int[] data = {45, 12, 89, 33, 7};
        
        int index = search(data, 33);
        System.out.println("Found at index: " + index); // Output: 3
    }
}

Common Pitfalls

  • Using Linear Search on massive datasets when the data is already sorted. If you know the array is sorted, using a Linear Search is a massive waste of processing power. You should always use Binary Search (O(log N)) for sorted data.
  • Returning boolean false instead of -1 when searching for indices. A common beginner mistake is mixing up search functions that return the existence of an item (boolean) with functions that return the location of an item (integer). If returning an index, always use -1 to represent 'not found', as 0 is a valid index.
  • Comparing Objects using == instead of .equals(). If your array contains Strings or custom objects, if (arr[i] == target) will check for memory reference equality, not value equality. This will fail silently. Always use if (arr[i].equals(target)) for objects.

Interview Questions

What is the Best Case, Worst Case, and Average Case time complexity for Linear Search?

Best Case: O(1) if the target is the very first element. Worst Case: O(N) if the target is the very last element or not in the array. Average Case: O(N/2), which mathematically simplifies to O(N).

Can Linear Search be used on a Singly Linked List?

Yes, absolutely. Since a Linked List only supports sequential access anyway, traversing from head to tail node-by-node is the only way to search it. The time complexity remains O(N).

Real-World Example

When a teacher scans a messy, unalphabetized stack of test papers looking for 'John Doe', they are performing a physical linear search. They must check every paper one by one. In software, searching a small, unsorted configuration file for a specific key-value pair uses linear search.

example
java
public String findConfigValue(List<ConfigOption> config, String targetKey) {
    // The config list is small and unsorted
    for (ConfigOption option : config) {
        if (option.key.equals(targetKey)) {
            return option.value;
        }
    }
    return "DEFAULT_VALUE";
}

Check Your Knowledge

Test your understanding of Linear Search with these quick questions.

Question 1

Does Linear Search require the array to be sorted beforehand?

Question 2

What is the worst-case time complexity of Linear Search?

Question 3

Why do we typically return `-1` if the item is not found in an array?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A