Code Logo

Find Target Index

Published at19 Apr 2026
Searching & Sorting Hard 9 views
Like0

Searching for something in a sorted list is much faster than looking through a random mess. In Find Target Index, you will implement an efficient way to find exactly where a specific number is hiding inside a pre-sorted array.

Instead of checking every single item from start to finish, you can use a "divide and conquer" strategy. By looking at the middle element, you can immediately rule out half of the list and zero in on the target twice as fast. It is a powerful logic that is used in almost every piece of software today.

For example, if you are looking for 30 in the list [10, 20, 30, 40, 50], your algorithm should tell you that it is sitting at index 3. If the number isn’t there at all, you will just return -1 to indicate it couldn’t be found.

Learn about our pseudocode specification
Guide

Algorithm Flow

Recommendation Algorithm Flow for Find Target Index
Recommendation Algorithm Flow for Find Target Index

Solution Approach

When searching in a sorted list, Binary Search is far more efficient than a linear scan because it uses a divide-and-conquer strategy.

while low <= high do
   mid <- (low + high) DIV 2
   if arr[mid] = target then
      return mid
   else if arr[mid] < target then
      low <- mid + 1
   else
      high <- mid - 1
   endif
endwhile
return -1

The algorithm maintains two pointers, low and high, to define the search space. In each step, it checks the middle element. If the target is not found, it narrows the search to either the lower or upper half of the remaining elements. This reduces the search space logarithmically, achieving O(log n) performance.

Best Answers

Pseudocode - Approach 1
program search_data
dictionary
   n, target, low, high, mid, pos: integer
   arr: array[1..100] of integer
algorithm
   input(n)
   for low <- 1 to n do input(arr[low]) endfor
   input(target)
   low <- 1
   high <- n
   pos <- -1
   while (low <= high) AND (pos = -1) do
      mid <- (low + high) DIV 2
      if arr[mid] = target then pos <- mid
      else if arr[mid] < target then low <- mid + 1
      else high <- mid - 1 endif
      endif
   endwhile
   output(pos)
endprogram