Leetcode Explanation and Solution Q1. Search Insert Position and Q2. Two Sum
Introduction
Hey Guys welcome back to my new Blog in this blog i am gonna explain 2 Questions from Leetcode Which are :
- Q1. Search Insert Position
- Q2. Two Sum
Q1. Search Insert Position

In image above you all can see the question and its written Sorted Array, Rule no. 1 - If array is sorted 95% of Time Apply Binary Search
Explanation and Solution of Q1. Search Insert Position
Explanation of question: In this question you have to write an Algorithm such that it would return the index where this number should be placed in array
First see all the things given in Question:
- Array is Sorted
- Target Value is given
- Return index where number would be inserted
- You must write an algorithm with O(log n) runtime complexity.
How you would solve this question: Write the algorithm which finds floor of target and then increment the answer by +1
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) -1
while start <= end:
mid = (end + start)//2
if nums[mid] > target:
end = mid - 1
elif nums[mid] < target:
start = mid + 1
else :
return mid
return end+1
Q2. Two Sum

Explanation and Solution of Question
Explanation of Question So in this question you have to return two indices which sum up to target and no repeated elements
Hints in the Question
- Array is not sorted
- No repeated Elements
- Two given: Array and Target
- Only specific two number can sum up to target ,that means only one solution
How you would solve this Question: Take two loops one loop start from index 0 and other from index 1 or the second loop start from first loop start index + 1 Write an If statement such that if sum of two index of loops == target return that indxes
Code
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return([i,j])
Outro
I publish Blog related to Machine learning ,Open Source and DSA , If you liked my content do connect me on Twitter
更多推荐

所有评论(0)