Skip to content

Instantly share code, notes, and snippets.

@KeshariPiyush24
Last active September 21, 2024 05:28
Show Gist options
  • Save KeshariPiyush24/f507f939a6f7ab3a0301698fedf21046 to your computer and use it in GitHub Desktop.
Save KeshariPiyush24/f507f939a6f7ab3a0301698fedf21046 to your computer and use it in GitHub Desktop.
Search Insert Position

Question: 35. Search Insert Position

Intution:

Time Complexity: $$O(log(n))$$

Space Complexity: $$O(1)$$

Solution:

class Solution {
    public int searchInsert(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (target < nums[mid]) high = mid - 1;
            else if (target > nums[mid]) low = mid + 1;
            else return mid;
        }
        return low;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment