878239. Array Searching

Basic

Array Searching

Slug: search-an-element-in-an-array-1587115621--133819 Difficulty: Basic Id: 878239 Topic Tags: Arrays, Searching, Data Structures, Algorithms Company Tags: None

Summary

The problem involves searching for an element in an array. Given a sorted array and a target value, the task is to find the index of the target value if it exists in the array.

Detailed Explanation

To solve this problem, we can use a simple linear search algorithm. The basic idea is to iterate through the array, comparing each element with the target value until we find a match or reach the end of the array.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, start and end, to represent the beginning and end of the array.
  2. Calculate the middle index of the current range using the formula (start + end) / 2.
  3. Compare the element at the middle index with the target value.
  4. If the elements match, return the middle index as the result.
  5. If the target value is less than the middle element, update the end pointer to the middle index minus one and repeat steps 2-4.
  6. If the target value is greater than the middle element, update the start pointer to the middle index plus one and repeat steps 2-4.
  7. If the target value is not found after searching the entire array, return -1 (or a special value indicating that the element was not found).

Time complexity: O(n), where n is the length of the array.

Space complexity: O(1), as we only use a few extra variables to store the pointers and the middle index.

Optimized Solutions

Java

View on GeeksforGeeks
public int search(int[] nums, int target) {
    int start = 0;
    int end = nums.length - 1;

    while (start <= end) {
        int mid = start + (end - start) / 2;

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

        if (target < nums[mid]) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }

    return -1; // not found
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.