Open In App

Improving Linear Search Technique

A linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched. It is observed that when searching for a key element, then there is a possibility for searching the same key element again and again.

The goal is that if the same element is searched again then the operation must take lesser time. Therefore, in such a case, Linear Search can be improved by using the following two methods: 



  1. Transposition
  2. Move to Front

Transposition:

In transposition, if the key element is found, it is swapped to the element an index before to increase in a number of search count for a particular key, the search operation also optimizes and keep moving the element to the starting of the array where the searching time complexity would be of constant time. 

For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps: 



Below is the implementation of the above algorithm discussed:




// C++ program for transposition to
// improve the Linear Search Algorithm
#include <iostream>
using namespace std;
 
// Structure of the array
struct Array {
 
    int A[10];
    int size;
    int length;
};
 
// Function to print the array element
void Display(struct Array arr)
{
    int i;
 
    // Traverse the array arr[]
    for (i = 0; i < arr.length; i++) {
        cout <<" "<< arr.A[i];
    }
    cout <<"\n";
}
 
// Function that swaps two elements
// at different addresses
void swap(int* x, int* y)
{
    // Store the value store at
    // x in a variable temp
    int temp = *x;
 
    // Swapping of value
    *x = *y;
    *y = temp;
}
 
// Function that performs the Linear
// Search Transposition
int LinearSearchTransposition(
    struct Array* arr, int key)
{
    int i;
 
    // Traverse the array
    for (i = 0; i < arr->length; i++) {
 
        // If key is found, then swap
        // the element with it's
        // previous index
        if (key == arr->A[i]) {
 
            // If key is first element
            if (i == 0)
                return i;
 
            swap(&arr->A[i],
                 &arr->A[i - 1]);
 
            return i;
        }
    }
    return -1;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    struct Array arr
        = { { 2, 23, 14, 5, 6, 9, 8, 12 },
            10,
            8 };
 
    cout <<"Elements before Linear"
           " Search Transposition: ";
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
 
    // Function Call for transposition
    LinearSearchTransposition(&arr, 14);
 
    cout <<"Elements after Linear"
           " Search Transposition: ";
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
    return 0;
}
 
// this code is contributed by shivanisinghss2110




// C program for transposition to
// improve the Linear Search Algorithm
#include <stdio.h>
 
// Structure of the array
struct Array {
 
    int A[10];
    int size;
    int length;
};
 
// Function to print the array element
void Display(struct Array arr)
{
    int i;
 
    // Traverse the array arr[]
    for (i = 0; i < arr.length; i++) {
        printf("%d ", arr.A[i]);
    }
    printf("\n");
}
 
// Function that swaps two elements
// at different addresses
void swap(int* x, int* y)
{
    // Store the value store at
    // x in a variable temp
    int temp = *x;
 
    // Swapping of value
    *x = *y;
    *y = temp;
}
 
// Function that performs the Linear
// Search Transposition
int LinearSearchTransposition(
    struct Array* arr, int key)
{
    int i;
 
    // Traverse the array
    for (i = 0; i < arr->length; i++) {
 
        // If key is found, then swap
        // the element with it's
        // previous index
        if (key == arr->A[i]) {
 
            // If key is first element
            if (i == 0)
                return i;
 
            swap(&arr->A[i],
                 &arr->A[i - 1]);
 
            return i;
        }
    }
    return -1;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    struct Array arr
        = { { 2, 23, 14, 5, 6, 9, 8, 12 },
            10,
            8 };
 
    printf("Elements before Linear"
           " Search Transposition: ");
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
 
    // Function Call for transposition
    LinearSearchTransposition(&arr, 14);
 
    printf("Elements after Linear"
           " Search Transposition: ");
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
    return 0;
}




// Java program for transposition
// to improve the Linear Search
// Algorithm
class GFG{
 
// Structure of the
// array
static class Array
{
  int []A = new int[10];
  int size;
  int length;
  Array(int []A, int size,
        int length)
  {
    this.A = A;
    this.size = size;
    this.length = length;
  }
};
 
// Function to print the
// array element
static void Display(Array arr)
{
  int i;
 
  // Traverse the array arr[]
  for (i = 0; i < arr.length; i++)
  {
    System.out.printf("%d ",
                      arr.A[i]);
  }
  System.out.printf("\n");
}
 
// Function that performs the Linear
// Search Transposition
static int LinearSearchTransposition(Array arr,
                                     int key)
{
  int i;
 
  // Traverse the array
  for (i = 0; i < arr.length; i++)
  {
    // If key is found, then swap
    // the element with it's
    // previous index
    if (key == arr.A[i])
    {
      // If key is first element
      if (i == 0)
        return i;
      int temp = arr.A[i];
      arr.A[i] = arr.A[i - 1];
      arr.A[i - 1] = temp;
      return i;
    }
  }
  return -1;
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array arr[]
  int tempArr[] = {2, 23, 14, 5,
                   6, 9, 8, 12};
  Array arr = new Array(tempArr,
                        10, 8);
 
  System.out.printf("Elements before Linear" +
                    " Search Transposition: ");
 
  // Function Call for displaying
  // the array arr[]
  Display(arr);
 
  // Function Call for transposition
  LinearSearchTransposition(arr, 14);
 
  System.out.printf("Elements after Linear" +
                    " Search Transposition: ");
 
  // Function Call for displaying
  // the array arr[]
  Display(arr);
}
}
 
// This code is contributed by Princi Singh




# Python3 program for transposition to
# improve the Linear Search Algorithm
 
 
# Structure of the array
class Array :
    def __init__(self,a=[0]*10,size=10,l=0) -> None:
        self.A=a
        self.size=size
        self.length=l
 
# Function to print array element
def Display(arr):
 
    # Traverse the array arr[]
    for i in range(arr.length) :
        print(arr.A[i],end=" ")
     
    print()
 
 
# Function that performs the Linear
# Search Transposition
def LinearSearchTransposition(arr, key):
 
    # Traverse the array
    for i in range(arr.length) :
 
        # If key is found, then swap
        # the element with it's
        # previous index
        if (key == arr.A[i]) :
 
            # If key is first element
            if (i == 0):
                return i
 
            arr.A[i],arr.A[i - 1]=arr.A[i - 1],arr.A[i]
 
            return i
         
     
    return -1
 
 
# Driver Code
if __name__ == '__main__':
    # Given array arr[]
    arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8)
 
    print("Elements before Linear Search Transposition: ")
 
    # Function Call for displaying
    # the array arr[]
    Display(arr)
 
    # Function Call for transposition
    LinearSearchTransposition(arr, 14)
 
    print("Elements after Linear Search Transposition: ")
 
    # Function Call for displaying
    # the array arr[]
    Display(arr)




// C# program for transposition
// to improve the Linear Search
// Algorithm
using System;
 
class GFG{
 
// Structure of the
// array
public class Array
{
    public int []A = new int[10];
    public int size;
    public int length;
     
    public Array(int []A, int size,
                 int length)
    {
        this.A = A;
        this.size = size;
        this.length = length;
    }
};
 
// Function to print the
// array element
static void Display(Array arr)
{
    int i;
     
    // Traverse the array []arr
    for(i = 0; i < arr.length; i++)
    {
        Console.Write(arr.A[i] + " ");
    }
    Console.Write("\n");
}
 
// Function that performs the Linear
// Search Transposition
static int LinearSearchTransposition(Array arr,
                                     int key)
{
    int i;
     
    // Traverse the array
    for(i = 0; i < arr.length; i++)
    {
         
        // If key is found, then swap
        // the element with it's
        // previous index
        if (key == arr.A[i])
        {
             
            // If key is first element
            if (i == 0)
                return i;
                 
            int temp = arr.A[i];
            arr.A[i] = arr.A[i - 1];
            arr.A[i - 1] = temp;
            return i;
        }
    }
    return -1;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []tempArr = { 2, 23, 14, 5,
                      6, 9, 8, 12 };
    Array arr = new Array(tempArr, 10, 8);
     
    Console.Write("Elements before Linear " +
                  "Search Transposition: ");
     
    // Function Call for displaying
    // the array []arr
    Display(arr);
     
    // Function Call for transposition
    LinearSearchTransposition(arr, 14);
     
    Console.Write("Elements after Linear " +
                  "Search Transposition: ");
     
    // Function Call for displaying
    // the array []arr
    Display(arr);
}
}
 
// This code is contributed by Amit Katiyar




// Javascript program for transposition
// to improve the Linear Search
// Algorithm
 
// Structure of the
// array
class Array {
    constructor(A, size, length) {
        this.A = A;
        this.size = size;
        this.length = length;
    }
};
 
// Function to print the
// array element
function Display(arr) {
    let i;
 
    // Traverse the array arr[]
    for (i = 0; i < arr.length; i++) {
        console.log(arr.A[i] + " ");
    }
    console.log("<br>");
}
 
// Function that performs the Linear
// Search Transposition
function LinearSearchTransposition(arr, key) {
    let i;
 
    // Traverse the array
    for (i = 0; i < arr.length; i++) {
        // If key is found, then swap
        // the element with it's
        // previous index
        if (key == arr.A[i]) {
            // If key is first element
            if (i == 0)
                return i;
            let temp = arr.A[i];
            arr.A[i] = arr.A[i - 1];
            arr.A[i - 1] = temp;
            return i;
        }
    }
    return -1;
}
 
// Driver Code
 
// Given array arr[]
let tempArr = [2, 23, 14, 5, 6, 9, 8, 12];
let arr = new Array(tempArr, 10, 8);
 
console.log("Elements before Linear" +
    " Search Transposition: ");
 
// Function Call for displaying
// the array arr[]
Display(arr);
 
// Function Call for transposition
LinearSearchTransposition(arr, 14);
 
console.log("Elements after Linear" + " Search Transposition: ");
 
// Function Call for displaying
// the array arr[]
Display(arr);
 
// This code is contributed by Saurabh Jaiswal

Output
Elements before Linear Search Transposition:  2 23 14 5 6 9 8 12
Elements after Linear Search Transposition:  2 14 23 5 6 9 8 12

Move to Front/Head:

In this method, if the key element is found then it is directly swapped with the index 0, so that the next consecutive time, search operation for the same key element is of O(1), i.e., constant time. 

For Example: If the array arr[] is {2, 5, 7, 1, 6, 4, 5, 8, 3, 7} and let the key to be searched is 4, then below are the steps: 




// C program to implement the move to
// front to optimized Linear Search
#include <iostream>
using namespace std;
 
// Structure of the array
struct Array {
 
    int A[10];
    int size;
    int length;
};
 
// Function to print the array element
void Display(struct Array arr)
{
    int i;
 
    // Traverse the array arr[]
    for (i = 0; i < arr.length; i++) {
        cout <<" "<< arr.A[i];
    }
    cout <<"\n";
}
 
// Function that swaps two elements
// at different addresses
void swap(int* x, int* y)
{
    // Store the value store at
    // x in a variable temp
    int temp = *x;
 
    // Swapping of value
    *x = *y;
    *y = temp;
}
 
// Function that performs the move to
// front operation for Linear Search
int LinearSearchMoveToFront(
    struct Array* arr, int key)
{
    int i;
 
    // Traverse the array
    for (i = 0; i < arr->length; i++) {
 
        // If key is found, then swap
        // the element with 0-th index
        if (key == arr->A[i]) {
            swap(&arr->A[i], &arr->A[0]);
            return i;
        }
    }
    return -1;
}
 
// Driver code
int main()
{
    // Given array arr[]
    struct Array arr
        = { { 2, 23, 14, 5, 6, 9, 8, 12 },
            10,
            8 };
 
    cout <<"Elements before Linear"
           " Search Move To Front: ";
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
 
    // Function Call for Move to
    // front operation
    LinearSearchMoveToFront(&arr, 14);
 
    cout <<"Elements after Linear"
           " Search Move To Front: ";
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
    return 0;
}
 
// This code is contributed by shivanisinghss2110




// C program to implement the move to
// front to optimized Linear Search
#include <stdio.h>
 
// Structure of the array
struct Array {
 
    int A[10];
    int size;
    int length;
};
 
// Function to print the array element
void Display(struct Array arr)
{
    int i;
 
    // Traverse the array arr[]
    for (i = 0; i < arr.length; i++) {
        printf("%d ", arr.A[i]);
    }
    printf("\n");
}
 
// Function that swaps two elements
// at different addresses
void swap(int* x, int* y)
{
    // Store the value store at
    // x in a variable temp
    int temp = *x;
 
    // Swapping of value
    *x = *y;
    *y = temp;
}
 
// Function that performs the move to
// front operation for Linear Search
int LinearSearchMoveToFront(
    struct Array* arr, int key)
{
    int i;
 
    // Traverse the array
    for (i = 0; i < arr->length; i++) {
 
        // If key is found, then swap
        // the element with 0-th index
        if (key == arr->A[i]) {
            swap(&arr->A[i], &arr->A[0]);
            return i;
        }
    }
    return -1;
}
 
// Driver code
int main()
{
    // Given array arr[]
    struct Array arr
        = { { 2, 23, 14, 5, 6, 9, 8, 12 },
            10,
            8 };
 
    printf("Elements before Linear"
           " Search Move To Front: ");
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
 
    // Function Call for Move to
    // front operation
    LinearSearchMoveToFront(&arr, 14);
 
    printf("Elements after Linear"
           " Search Move To Front: ");
 
    // Function Call for displaying
    // the array arr[]
    Display(arr);
    return 0;
}




// Java program to implement
// the move to front to optimized
// Linear Search
class GFG{
 
// Structure of the array
static class Array
{
  int []A = new int[10];
  int size;
  int length;
  Array(int []A, int size,
        int length)
  {
    this.A = A;
    this.size = size;
    this.length = length;
  }
};
 
// Function to print the
// array element
static void Display(Array arr)
{
  int i;
 
  // Traverse the array arr[]
  for (i = 0;
       i < arr.length; i++)
  {
    System.out.printf("%d ", arr.A[i]);
  }
  System.out.printf("\n");
}
 
// Function that performs the
// move to front operation for
// Linear Search
static int LinearSearchMoveToFront(Array arr,
                                   int key)
{
  int i;
 
  // Traverse the array
  for (i = 0; i < arr.length; i++)
  {
    // If key is found, then swap
    // the element with 0-th index
    if (key == arr.A[i])
    {
      int temp = arr.A[i];
      arr.A[i] = arr.A[0];
      arr.A[0] = temp;
      return i;
    }
  }
  return -1;
}
 
// Driver code
public static void main(String[] args)
{
  // Given array arr[]
  int a[] = {2, 23, 14, 5,
             6, 9, 8, 12 };
  Array arr = new Array(a, 10, 8);
 
  System.out.printf("Elements before Linear" +
                    " Search Move To Front: ");
 
  // Function Call for
  // displaying the array
  // arr[]
  Display(arr);
 
  // Function Call for Move
  // to front operation
  LinearSearchMoveToFront(arr, 14);
 
  System.out.printf("Elements after Linear" +
                    " Search Move To Front: ");
 
  // Function Call for displaying
  // the array arr[]
  Display(arr);
}
}
 
// This code is contributed by gauravrajput1




# Python3 program for transposition to
# improve the Linear Search Algorithm
 
 
# Structure of the array
class Array :
    def __init__(self,a=[0]*10,size=10,l=0) -> None:
        self.A=a
        self.size=size
        self.length=l
 
# Function to print array element
def Display(arr):
 
    # Traverse the array arr[]
    for i in range(arr.length) :
        print(arr.A[i],end=" ")
     
    print()
 
 
# Function that performs the move to
# front operation for Linear Search
def LinearSearchMoveToFront(arr, key:int):
 
    # Traverse the array
    for i in range(arr.length) :
 
        # If key is found, then swap
        # the element with 0-th index
        if (key == arr.A[i]) :
            arr.A[i], arr.A[0]=arr.A[0],arr.A[i]
            return i
         
     
    return -1
 
 
# Driver Code
if __name__ == '__main__':
    # Given array arr[]
    arr=Array([2, 23, 14, 5, 6, 9, 8, 12], 10, 8)
 
    print("Elements before Linear Search Transposition: ",end='')
 
    # Function Call for displaying
    # the array arr[]
    Display(arr)
 
    # Function Call for transposition
    LinearSearchMoveToFront(arr, 14)
 
    print("Elements after Linear Search Transposition: ",end='')
 
    # Function Call for displaying
    # the array arr[]
    Display(arr)




// C# program to implement
// the move to front to optimized
// Linear Search
using System;
class GFG{
 
// Structure of the array
public class Array
{
  public int []A = new int[10];
  public int size;
  public int length;
  public Array(int []A,
               int size,
               int length)
  {
    this.A = A;
    this.size = size;
    this.length = length;
  }
};
 
// Function to print the
// array element
static void Display(Array arr)
{
  int i;
 
  // Traverse the array []arr
  for (i = 0;
       i < arr.length; i++)
  {
    Console.Write(" " + arr.A[i]);
  }
  Console.Write("\n");
}
 
// Function that performs the
// move to front operation for
// Linear Search
static int LinearSearchMoveToFront(Array arr,
                                   int key)
{
  int i;
 
  // Traverse the array
  for (i = 0; i < arr.length; i++)
  {
    // If key is found, then swap
    // the element with 0-th index
    if (key == arr.A[i])
    {
      int temp = arr.A[i];
      arr.A[i] = arr.A[0];
      arr.A[0] = temp;
      return i;
    }
  }
  return -1;
}
 
// Driver code
public static void Main(String[] args)
{
  // Given array []arr
  int []a = {2, 23, 14, 5,
             6, 9, 8, 12 };
   
  Array arr = new Array(a, 10, 8);
  Console.Write("Elements before Linear" +
                " Search Move To Front: ");
 
  // Function Call for
  // displaying the array
  // []arr
  Display(arr);
 
  // Function Call for Move
  // to front operation
  LinearSearchMoveToFront(arr, 14);
 
  Console.Write("Elements after Linear" +
                " Search Move To Front: ");
 
  // Function Call for displaying
  // the array []arr
  Display(arr);
}
}
 
// This code is contributed by gauravrajput1




// JavaScript implementation of Move to Front optimization for Linear Search
 
// Structure of the array
class Array {
constructor(A, size, length) {
this.A = A;
this.size = size;
this.length = length;
}
}
 
// Function to print the array element
const display = (arr) => {
// Traverse the array arr[]
for (let i = 0; i < arr.length; i++) {
console.log(arr.A[i]);
}
console.log("\n");
};
 
// Function that performs the move to front operation for Linear Search
const linearSearchMoveToFront = (arr, key) => {
// Traverse the array
for (let i = 0; i < arr.length; i++) {
// If key is found, then swap the element with 0-th index
if (key === arr.A[i]) {
let temp = arr.A[i];
arr.A[i] = arr.A[0];
arr.A[0] = temp;
return i;
}
}
return -1;
};
 
// Given array arr[]
const a = [2, 23, 14, 5, 6, 9, 8, 12];
const arr = new Array(a, 10, 8);
 
console.log("Elements before Linear Search Move To Front: ");
 
// Function Call for displaying the array arr[]
display(arr);
 
// Function Call for Move to front operation
linearSearchMoveToFront(arr, 14);
 
console.log("Elements after Linear Search Move To Front: ");
 
// Function Call for displaying the array arr[]
display(arr);

Output
Elements before Linear Search Move To Front:  2 23 14 5 6 9 8 12
Elements after Linear Search Move To Front:  14 23 2 5 6 9 8 12

Time Complexity: O(N)  
Auxiliary Space: O(1)

Using Hash Tables:

If the list is large and we need to perform frequent searches, we can create a hash table that maps each element to its position in the list. This way, we can find the position of an element in constant time by looking up its value in the hash table.




#include <iostream>
#include <unordered_map>
#include <vector>
 
int linearSearchWithHashTable(std::vector<int>& arr, int target) {
    // Create a hash table to map each element to its position
    std::unordered_map<int, int> hashTable;
    for (int i = 0; i < arr.size(); i++) {
        hashTable[arr[i]] = i;
    }
 
    // Search for the target element in the hash table
    if (hashTable.find(target) != hashTable.end()) {
        return hashTable[target];
    } else {
        return -1;
    }
}
 
int main() {
    std::vector<int> arr = {1, 5, 3, 9, 2, 7};
    int target = 9;
 
    int index = linearSearchWithHashTable(arr, target);
    if (index != -1) {
        std::cout << "Found " << target << " at index " << index << std::endl;
    } else {
        std::cout << target << " not found in the list" << std::endl;
    }
 
    return 0;
}
//contributed by P S PAVAN




import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
 
class Gfg {
    static int linearSearchWithHashTable(ArrayList<Integer> arr, int target) {
        // Create a hash table to map each element to its position
        Map<Integer, Integer> hashTable = new HashMap<Integer, Integer>();
        for (int i = 0; i < arr.size(); i++) {
            hashTable.put(arr.get(i), i);
        }
 
        // Search for the target element in the hash table
        if (hashTable.containsKey(target)) {
            return hashTable.get(target);
        } else {
            return -1;
        }
    }
 
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(1);
        arr.add(5);
        arr.add(3);
        arr.add(9);
        arr.add(2);
        arr.add(7);
        int target = 9;
 
        int index = linearSearchWithHashTable(arr, target);
        if (index != -1) {
            System.out.println("Found " + target + " at index " + index);
        } else {
            System.out.println(target + " not found in the list");
        }
    }
}




from typing import List
 
def linear_search_with_hash_table(arr: List[int], target: int) -> int:
    # Create a hash table to map each element to its position
    hash_table = {}
    for i in range(len(arr)):
        hash_table[arr[i]] = i
 
    # Search for the target element in the hash table
    if target in hash_table:
        return hash_table[target]
    else:
        return -1
 
# Main function
if __name__ == '__main__':
    arr = [1, 5, 3, 9, 2, 7]
    target = 9
 
    index = linear_search_with_hash_table(arr, target)
    if index != -1:
        print("Found", target, "at index", index)
    else:
        print(target, "not found in the list")




// C# implementation of above approach
using System;
using System.Collections.Generic;
 
class Gfg {
static int LinearSearchWithHashTable(List<int> arr, int target) {
// Create a dictionary to map each element to its position
Dictionary<int, int> hashTable = new Dictionary<int, int>();
for (int i = 0; i < arr.Count; i++) {
hashTable.Add(arr[i], i);
}
    // Search for the target element in the hash table
    if (hashTable.ContainsKey(target)) {
        return hashTable[target];
    } else {
        return -1;
    }
}
 
 // Driver Code
public static void Main(string[] args) {
    List<int> arr = new List<int>();
    arr.Add(1);
    arr.Add(5);
    arr.Add(3);
    arr.Add(9);
    arr.Add(2);
    arr.Add(7);
    int target = 9;
 
    int index = LinearSearchWithHashTable(arr, target);
    if (index != -1) {
        Console.WriteLine("Found " + target + " at index " + index);
    } else {
        Console.WriteLine(target + " not found in the list");
    }
}
}




function linearSearchWithHashTable(arr, target) {
    // Create a hash table to map each element to its position
    const hashTable = {};
    for (let i = 0; i < arr.length; i++) {
        hashTable[arr[i]] = i;
    }
 
    // Search for the target element in the hash table
    if (hashTable[target] !== undefined) {
        return hashTable[target];
    } else {
        return -1;
    }
}
 
const arr = [1, 5, 3, 9, 2, 7];
const target = 9;
 
const index = linearSearchWithHashTable(arr, target);
if (index !== -1) {
    console.log(`Found ${target} at index ${index}`);
} else {
    console.log(`${target} not found in the list`);
}

Output
Found 9 at index 3

Explination of Code:

In this implementation, we use the std::unordered_map container from the C++ standard library to create a hash table that maps each element in the list to its position. We then search for the target element in the hash table using its value as a key. If the element is found, we return its position. Otherwise, we return -1 to indicate that the element is not in the list.

Using a hash table can significantly improve the performance of linear search, especially for large lists or when we need to perform frequent searches. The time complexity of linear search using hash tables is O(n) for building the hash table and O(1) for each search, assuming that the hash function has a good distribution and the hash table has sufficient capacity to avoid collisions.

Time Complexity: O(N)  
Auxiliary Space: O(1)


Article Tags :