Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/search-insert-position-of-k-in-a-sorted-array/1
Search insert position of K in a sorted array
Difficulty: Easy Accuracy: 38.99%
Given a sorted array arr of distinct integers and an integer k, find the index of k if it is present in the arr[]. If not, return the index where k should be inserted to maintain the sorted order.
Examples :
Input: arr[] = [1, 3, 5, 6], k = 5
Output: 2
Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is 2.
Input: arr[] = [1, 3, 5, 6], k = 2
Output: 1
Explanation: The element 2 is not present in the array, but inserting it at index 1 will maintain the sorted order.
Input: arr[] = [2, 6, 7, 10, 14], k = 15
Output: 5
Explanation: The element 15 is not present in the array, but inserting it after index 4 will maintain the sorted order.
Constraints:
1 β€ arr.size() β€ 104
-103 β€ arr[i] β€ 103
-103 β€ k β€ 103
Solution:
class Solution:
def searchInsertK(self, arr, k):
l, r = 0, len(arr) - 1
while l <= r:
m = (l + r) // 2
if arr[m] == k:
return m
elif arr[m] < k:
l = m + 1
else:
r = m - 1
return l
Top comments (0)