Search Insert Position

Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You must write an algorithm with O(log n) runtime complexity.

LeetCode Problem - 45 : Link | Click Here

class Solution {
    public int searchInsert(int[] nums, int target) {
        // Initialize result variable to store the final index
        int result = 0;

        // First loop to search for the target in the array
        for (int i = 0; i < nums.length; i++) {
            // If the target is found, store the index and exit the loop
            if (nums[i] == target) {
                result = i;
                break;
            }
        }

        // If the target was not found in the first loop
        if (result == 0) {
            // Second loop to find the correct index to insert the target
            for (int j = 0; j < nums.length; j++) {
                // If the current element is greater than or equal to the target
                if (nums[j] >= target) {
                    // Store the current index and exit the loop
                    result = j;
                    break;
                } else {
                    // If the current element is less than the target, set result to the end of the array
                    result = nums.length;
                }
            }
        }

        // Return the final result which represents the index to insert the target
        return result;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!