Skip to content

Commit 081ead6

Browse files
Merge pull request #583 from priyashuu/insert
Add Search Insert Position algorithm implementation in Java
2 parents 4d6d9f5 + ac48a88 commit 081ead6

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* Algorithm Name:Search Insert Position .
3+
* Programming Language: Java
4+
* Category: Array
5+
* Difficulty Level: Easy
6+
*
7+
* Author: Priya Rani
8+
*
9+
* Algorithm Description: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.
10+
11+
You must write an algorithm with O(log n) runtime complexity.
12+
13+
14+
15+
16+
* Time Complexity: O(log n) Uses binary search, halving the search space each step
17+
* Space complexity: O(1) No extra data structures used, only a few variables
18+
*/
19+
public class SearchInsertPosition {
20+
public int searchInsert(int[] nums, int target) {
21+
int left = 0, right = nums.length - 1;
22+
23+
while (left <= right) {
24+
int mid = left + (right - left) / 2;
25+
26+
if (nums[mid] == target) {
27+
return mid;
28+
} else if (nums[mid] < target) {
29+
left = mid + 1;
30+
} else {
31+
right = mid - 1;
32+
}
33+
}
34+
35+
return left;
36+
}
37+
38+
public static void main(String[] args) {
39+
SearchInsertPosition solution = new SearchInsertPosition();
40+
int[] nums = {1, 3, 5, 6};
41+
int target = 5;
42+
43+
System.out.println("Output: " + solution.searchInsert(nums, target));
44+
}
45+
}

0 commit comments

Comments
 (0)