Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

35 search insert position #67

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions LeetCode/Search-Insert-Position/C++/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Search Insert Position

## Problem Description

Given a sorted array of distinct integers and a target value, your task is to return the index where the target value should be inserted into the array to maintain its sorted order. If the target value is already in the array, return its index.

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

**Example 1:**
Input: `nums = [1, 3, 5, 6]`, `target = 5`
Output: `2`

**Example 2:**
Input: `nums = [1, 3, 5, 6]`, `target = 2`
Output: `1`

## How to Run

1. Make sure you have a C++ compiler installed on your system, such as g++.

2. Clone this repository to your local machine or download the `SearchInsertPosition.cpp` file.

3. Open your terminal or command prompt.

4. Navigate to the directory where the `SearchInsertPosition.cpp` file is located.

5. Compile the C++ code using your compiler.

6. Run the program by executing the generated executable and passing in the sample input arrays and target values.

7. The program will execute and display the result, which is the index where the target element is or should be inserted to maintain the sorted order of the array.

## Example Usage
An example of how to use this program:

```shell
$ g++ SearchInsertPosition.cpp -o SearchInsertPosition
$ ./SearchInsertPosition
The index of the target element is: 2

```
## Approach

The approach to solving this problem efficiently involves using a binary search algorithm:

1. Initialize two pointers, `start` and `end`, to the beginning and end of the sorted array, respectively.

2. Enter a while loop as long as `start` is less than or equal to `end`.

3. Calculate the middle index, `mid`, as the average of `start` and `end`.

4. Check if the element at index `mid` is equal to the target:
- If they are equal, return `mid` because the target is found in the array.
- If the element at `mid` is less than the target, update `start` to `mid + 1` to search the end half of the array.
- If the element at `mid` is greater than the target, update `end` to `mid - 1` to search the start half of the array.

5. Repeat steps 3-4 until `start` is greater than `end`, indicating that the entire array has been searched.

6. If the target is not found, return `start`. This represents the index where the target should be inserted to maintain the sorted order.

## Complexity Analysis

- Time Complexity: O(log n)
- The binary search algorithm divides the search space in half with each iteration, leading to a logarithmic time complexity. The time complexity is proportional to the logarithm of the number of elements in the array.
- Space Complexity: O(1)
- The algorithm uses a constant amount of extra space for variables (`start`, `end`, `mid`) and does not depend on the size of the input array. Therefore, the space complexity is O(1).

---

This solution efficiently finds the index at which a target value should be inserted into a sorted array while maintaining a low time and space complexity, making it suitable for large sorted arrays.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
42 changes: 42 additions & 0 deletions LeetCode/Search-Insert-Position/C++/SearchInsertPosition.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <vector>
#include <iostream>
using namespace std;

class Solution
{
public:
int searchInsert(vector<int> &nums, int target)
{
int start = 0; // initialize start index of binary search
int end = nums.size() - 1; // initialize end index of binary search

while (start <= end) {
// perform binary search
int mid = start + (end - start) / 2; // calculate mid index

if (nums[mid] == target) {
// if element found at mid, return mid
return mid;
}
else if(nums[mid] < target){
// if element at mid is less than target, then target would be inserted after mid
start = mid + 1;
}
else {
// if element at mid is greater than target, then target would be inserted before mid
end = mid - 1;
}
}
// If target is not found and start is greater thsn end, it means target would be inserted at start index
return start;
}
};

int main() {
Solution solution; // Create object of Solution class
vector<int> nums = {1,3,5,6}; // Example input array
int target = 5; // Target element to search
int result = solution.searchInsert(nums, target);
cout << "The index of the target element is: " << result << endl; // Outputs the index of the target element or the index where it needs to be inserted
return 0;
}
28 changes: 28 additions & 0 deletions LeetCode/Search-Insert-Position/PROBLEM.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# 35. 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.

## Examples

### Example 1:

Input: `nums = [1,3,5,6]`, `target = 5`
Output: `2`

### Example 2:

Input: `nums = [1,3,5,6]`, `target = 2`
Output: `1`
### Example 3:

Input: `nums = [1,3,5,6]`, `target = 7`
Output: `4`


## Constraints:

-`1 <= nums.length <= 104`
- `104 <= nums[i] <= 104`
nums contains distinct values sorted in ascending order.
- `104 <= target <= 104`
Loading