Find the Target number in an Array
Last Updated :
23 Jul, 2025
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"
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();
OutputTarget 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.
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
OutputTarget 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 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.")
OutputTarget 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem