Open In App

Find the Target number in an Array

Last Updated : 16 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities.

Examples:

Input: Array: {10, 20, 30, 40, 50} , Target: 30
Output: “Target found at index 2”

Input: Array: {10, 20, 30, 40, 50}, Target: 40
Output: “Target found at index 3”

Linear Search Approach:

The basic idea to find a number in an array involves going through each element of the array one by one, and comparing them with the target value until a match is found.

Steps to solve the problem:

  • Start from the element, in the array.
  • Compare the element with the target value.
  • If they match, provide the index of that element.
  • If not, move on to the element in the array.
  • Repeat steps 2-4 until either you reach the end of the array or find a match.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

int binarySearch(int arr[], int left, int right, int target)
{
    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        }

        if (arr[mid] < target) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return -1;
}

// Drivers code
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 30;

    int index = binarySearch(arr, 0, n - 1, target);

    if (index != -1) {
        cout << "Target found at index " << index << endl;
    }
    else {
        cout << "Target not found in the array." << endl;
    }

    return 0;
}
Java
import java.util.Arrays;

public class LinearSearch {
    // Implementing linear search method
    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            // Check if the current element in the array matches the target
            if (arr[i] == target) {
                // If found, return the index where the target is located
                return i;
            }
        }
        // If the loop completes without finding the target, return -1 to indicate it's not in the array
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        int target = 30;

        // Call the linearSearch method to search for the target in the array
        int index = linearSearch(arr, target);

        if (index != -1) {
            // If the index is not -1, the target was found; print the index
            System.out.println("Number found at index " + index);
        } else {
            // If the index is -1, the target was not found; print a message indicating so
            System.out.println("Number not found in the array.");
        }
    }
}
Python
# Implementing optimized linear search method
def linear_search_optimized(arr, target):
    for i, num in enumerate(arr):
        if num == target:
            return i
    return -1


# Driver code
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    target = 30

    index = linear_search_optimized(arr, target)

    if index != -1:
        print("Number found at index {}".format(index))
    else:
        print("Number not found in the array.")
C#
using System;

class LinearSearch
{
    // Implementing linear search method
    static int LinearSearchFunc(int[] arr, int target)
    {
        // Iterate through the array to find the target element
        for (int i = 0; i < arr.Length; i++)
        {
            // If the current element matches the target, return its index
            if (arr[i] == target)
            {
                return i;
            }
        }
        // Return -1 if the target element is not found in the array
        return -1;
    }

    // Driver code
    static void Main()
    {
        int[] arr = { 10, 20, 30, 40, 50 };
        int target = 30;

        // Perform a linear search to find the target in the array
        int index = LinearSearchFunc(arr, target);

        // Output the result based on whether the target was found or not
        if (index != -1)
        {
            Console.WriteLine("Number found at index " + index);
        }
        else
        {
            Console.WriteLine("Number not found in the array.");
        }
    }
}
Javascript
// Implementing linear search method
function linearSearch(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        // Check if the current element in the array matches the target
        if (arr[i] === target) {
            // If found, return the index where the target is located
            return i;
        }
    }
    // If the loop completes without finding the target, return -1 to indicate it's not in the array
    return -1;
}

// Main function
function main() {
    const arr = [10, 20, 30, 40, 50];
    const target = 30;

    // Call the linearSearch method to search for the target in the array
    const index = linearSearch(arr, target);

    if (index !== -1) {
        // If the index is not -1, the target was found; print the index
        console.log("Number found at index " + index);
    } else {
        // If the index is -1, the target was not found; print a message indicating so
        console.log("Number not found in the array.");
    }
}

// Invoke the main function
main();

Output
Target found at index 2





Time Complexity: O(n) The time complexity of linear search is O(n) because in worst case scenarios you may need to check every element in the array.
Auxiliary space: O(1) The space requirement is O(1) as you only require a handful of variables to keep track of the loop.

Binary Search Approach:

When searching for a number in an array binary search is an algorithm that takes advantage of the sorted nature of the array. It does this by reducing the search space by half, in each iteration.

Steps to solve the problem:

  • Start by setting two pointers, “low” and “high ” to the last indices of the array
  • Calculate the middle index using the formula low+( high-low) / 2.
  • Compare the element at the index with the target value.
  • If they match, return the index as it indicates that we have found our target.
  • If the middle element is greater than the target value update “high” to be one less than “middle.”
  • If the middle element is less than the target value update “low” to be one more than “middle.”
  • Repeat steps 2-6 until either “low” becomes greater, than “high“. We find our target.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

int binarySearch(int arr[], int left, int right, int target)
{
    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (arr[mid] == target) {
            return mid;
        }

        if (arr[mid] < target) {
            left = mid + 1;
        }
        else {
            right = mid - 1;
        }
    }
    return -1;
}

// Drivers code
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 30;

    int index = binarySearch(arr, 0, n - 1, target);

    if (index != -1) {
        cout << "Target found at index " << index << endl;
    }
    else {
        cout << "Target not found in the array." << endl;
    }

    return 0;
}
Java
// Java code for the above approach:

class GFG {

    static int binarySearch(int arr[], int left, int right,
                            int target)
    {
        while (left <= right) {
            int mid = left + (right - left) / 2;

            if (arr[mid] == target) {
                return mid;
            }

            if (arr[mid] < target) {
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }

        return -1;
    }

    // Drivers code
    public static void main(String[] args)
    {
        int arr[] = { 10, 20, 30, 40, 50 };
        int n = arr.length;
        int target = 30;

        int index = binarySearch(arr, 0, n - 1, target);

        if (index != -1) {
            System.out.println("Target found at index "
                               + index);
        }
        else {
            System.out.println(
                "Target not found in the array.");
        }
    }
}

// This code is contributed by ragul21
Python
def binary_search(arr, left, right, target):
    while left <= right:
        mid = left + (right - left) // 2

        if arr[mid] == target:
            return mid

        if arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return -1

# Driver code
arr = [10, 20, 30, 40, 50]
n = len(arr)
target = 30

index = binary_search(arr, 0, n - 1, target)

if index != -1:
    print("Target found at index {}".format(index))
else:
    print("Target not found in the array.")
C#
using System;

class BinarySearchExample
{
    // Function to perform binary search on a sorted array
    static int BinarySearch(int[] arr, int left, int right, int target)
    {
        while (left <= right)
        {
            int mid = left + (right - left) / 2;

            // If target is found, return the index
            if (arr[mid] == target)
            {
                return mid;
            }

            // If target is greater, ignore the left half
            if (arr[mid] < target)
            {
                left = mid + 1;
            }
            // If target is smaller, ignore the right half
            else
            {
                right = mid - 1;
            }
        }
        // Target not found
        return -1;
    }

    // Driver code
    static void Main()
    {
        int[] arr = { 10, 20, 30, 40, 50 };
        int n = arr.Length;
        int target = 30;

        // Perform binary search
        int index = BinarySearch(arr, 0, n - 1, target);

        // Display the result
        if (index != -1)
        {
            Console.WriteLine($"Target found at index {index}");
        }
        else
        {
            Console.WriteLine("Target not found in the array.");
        }
    }
}
Javascript
// Function to perform binary search on a sorted array
function binarySearch(arr, left, right, target) {
    // Continue the search until the left pointer is less than or equal to the right pointer
    while (left <= right) {
        // Calculate the middle index of the current search range
        let mid = Math.floor(left + (right - left) / 2);

        // If the middle element is equal to the target, return its index
        if (arr[mid] === target) {
            return mid;
        }

        // If the middle element is less than the target, update the left pointer
        // to search in the right half of the array
        if (arr[mid] < target) {
            left = mid + 1;
        } 
        // If the middle element is greater than the target, update the right pointer
        // to search in the left half of the array
        else {
            right = mid - 1;
        }
    }

    // If the target is not found, return -1
    return -1;
}

// Driver code
let arr = [10, 20, 30, 40, 50];
let n = arr.length;
let target = 30;

// Call the binarySearch function to find the index of the target in the array
let index = binarySearch(arr, 0, n - 1, target);

// Display the result based on whether the target was found or not
if (index !== -1) {
    console.log("Target found at index " + index);
} else {
    console.log("Target not found in the array.");
}
//This Code is contributed by Prachi

Output
Target found at index 2





Time Complexity: O(log n) The time complexity of search is O(log n) when the array is sorted.
Auxiliary space: O(1) because we are using constant memory.

Hashing Approach:

Hashing is an approach that employs a hash function to map elements in an array to locations, within a data structure, usually known as a hash table. When you have an urgent need to locate a number this method proves to be highly effective.

Steps to solve the problem:

  • Start by setting up a hash table and create a hash function that maps values to indices, in the table.
  • Take each element from the array. Insert it into the hash table using the hash function.
  • When you want to find a number apply the hash function to that target value then locate its corresponding index in the hash table and finally check if the target value is stored there.
  • This method allows for retrieval of numbers when needed.

Implementation of the above approach:

C++
// C++ code for the above approach:
#include <iostream>
#include <unordered_map>
using namespace std;

int findNumber(int arr[], int n, int target)
{
    unordered_map<int, int> hT;
    for (int i = 0; i < n; i++) {
        hT[arr[i]] = i;
    }

    if (hT.find(target) != hT.end()) {
        return hT[target];
    }
    else {
        return -1;
    }
}

// Drivers code
int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 30;

    int index = findNumber(arr, n, target);

    // Function Call
    if (index != -1) {
        cout << "Target found at index " << index << endl;
    }
    else {
        cout << "Target not found in the array." << endl;
    }

    return 0;
}
Java
import java.util.HashMap;

public class Main {
    static int findNumber(int[] arr, int n, int target) {
        HashMap<Integer, Integer> hT = new HashMap<>();
        for (int i = 0; i < n; i++) {
            hT.put(arr[i], i);
        }

        if (hT.containsKey(target)) {
            return hT.get(target);
        } else {
            return -1;
        }
    }

    public static void main(String[] args) {
        int[] arr = { 10, 20, 30, 40, 50 };
        int n = arr.length;
        int target = 30;

        int index = findNumber(arr, n, target);

        // Function Call
        if (index != -1) {
            System.out.println("Target found at index " + index);
        } else {
            System.out.println("Target not found in the array.");
        }
    }
}
C#
using System;
using System.Collections.Generic;

class Program {
    static int FindNumber(int[] arr, int target)
    {
        Dictionary<int, int> hashTable
            = new Dictionary<int, int>();
        for (int i = 0; i < arr.Length; i++) {
            hashTable[arr[i]] = i;
        }

        if (hashTable.ContainsKey(target)) {
            return hashTable[target];
        }
        else {
            return -1;
        }
    }

    static void Main(string[] args)
    {
        int[] arr = { 10, 20, 30, 40, 50 };
        int target = 30;

        int index = FindNumber(arr, target);

        // Function Call
        if (index != -1) {
            Console.WriteLine("Target found at index "
                              + index);
        }
        else {
            Console.WriteLine(
                "Target not found in the array.");
        }
    }
}
Javascript
// Function to find the index of a target number in an array
function findNumber(arr, target) {
    // Create a new Map to store the array elements and their indices
    let elementMap = new Map();

    // Populate the Map with array elements and their indices
    for (let i = 0; i < arr.length; i++) {
        elementMap.set(arr[i], i);
    }

    // Check if the target number is present in the Map
    if (elementMap.has(target)) {
        // Return the index of the target number
        return elementMap.get(target);
    } else {
        // Return -1 if the target number is not found in the array
        return -1;
    }
}

// Driver code
function main() {
    // Example array
    const arr = [10, 20, 30, 40, 50];
    
    // Target number to be searched
    const target = 30;

    // Call the findNumber function to get the index of the target number
    const index = findNumber(arr, target);

    // Display the result based on the index value
    if (index !== -1) {
        console.log("Target found at index", index);
    } else {
        console.log("Target not found in the array.");
    }
}

// Run the main function
main();
Python3
def find_number(arr, target):
    hash_table = {}
    for i, num in enumerate(arr):
        hash_table[num] = i

    if target in hash_table:
        return hash_table[target]
    else:
        return -1

# Driver code
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    target = 30

    index = find_number(arr, target)

    # Function Call
    if index != -1:
        print(f"Target found at index {index}")
    else:
        print("Target not found in the array.")

Output
Target found at index 2





Time complexity: O(1), but in worst case scenarios it can degrade to linear (O(n)). Hashing usually provides O(1) time complexity, for retrieving data. However there are instances when hash collisions occur.
Auxiliary space: The space complexity is linear (O(n)) because you need to store all elements within the hash table.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads