700522. Operating an array

Easy

Operating an Array

Slug: operating-an-array

Difficulty: Easy

Id: 700522

Topic Tags: Arrays, Data Structures, Searching, Algorithms

Company Tags: None

Summary

Given a sorted array, we need to find the index at which a target element should be inserted to maintain the array's sort order. This problem involves searching and manipulating an array.

Detailed Explanation

The given array is already sorted in ascending or descending order. To solve this problem, we can use a binary search algorithm to find the correct position for the target element. Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, left and right, to represent the start and end of the array.
  2. Calculate the middle index of the current subarray using the formula (left + right) / 2.
  3. Compare the middle element with the target element:
    • If the target element is equal to the middle element, return the middle index as the correct position.
    • If the target element is less than the middle element, update right to the middle index - 1 and repeat steps 2-3.
    • If the target element is greater than the middle element, update left to the middle index + 1 and repeat steps 2-3.
  4. Continue this process until left and right converge or cross over each other.
  5. The correct position for the target element is the final value of left.

The time complexity of this algorithm is O(log n), where n is the length of the array, since we are dividing the search space in half at each step. The space complexity is O(1) as we only use a constant amount of space to store the pointers and the target element.

Optimized Solutions

Java

View on GeeksforGeeks
public int operatingArray(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

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

    return left;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.