Skip to content

Added tasks 34-51 #2

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

Merged
merged 1 commit into from
Feb 7, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
34\. Find First and Last Position of Element in Sorted Array

Medium

Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.

If `target` is not found in the array, return `[-1, -1]`.

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

**Example 1:**

**Input:** nums = [5,7,7,8,8,10], target = 8

**Output:** [3,4]

**Example 2:**

**Input:** nums = [5,7,7,8,8,10], target = 6

**Output:** [-1,-1]

**Example 3:**

**Input:** nums = [], target = 0

**Output:** [-1,-1]

**Constraints:**

* <code>0 <= nums.length <= 10<sup>5</sup></code>
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
* `nums` is a non-decreasing array.
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>

To solve this problem efficiently with a runtime complexity of O(log n), we can use binary search to find the starting and ending positions of the target value in the sorted array. Here are the steps:

### Approach:

1. **Binary Search for Starting Position:**
- Use binary search to find the starting position of the target value.
- When the target value is found, continue searching towards the left to find the leftmost occurrence.
- Update the left boundary to narrow down the search space.

2. **Binary Search for Ending Position:**
- Use binary search to find the ending position of the target value.
- When the target value is found, continue searching towards the right to find the rightmost occurrence.
- Update the right boundary to narrow down the search space.

3. **Handle Missing Target:**
- If the target value is not found, return [-1, -1].

### Python Code:

```python
class Solution:
def searchRange(self, nums, target):
def search_boundary(nums, target, is_left):
left, right = 0, len(nums) - 1
boundary = -1

while left <= right:
mid = (left + right) // 2

if nums[mid] == target:
boundary = mid
if is_left:
right = mid - 1
else:
left = mid + 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1

return boundary

left_boundary = search_boundary(nums, target, is_left=True)
right_boundary = search_boundary(nums, target, is_left=False)

return [left_boundary, right_boundary]

# Example Usage:
solution = Solution()

# Example 1:
nums1 = [5, 7, 7, 8, 8, 10]
target1 = 8
print(solution.searchRange(nums1, target1)) # Output: [3, 4]

# Example 2:
nums2 = [5, 7, 7, 8, 8, 10]
target2 = 6
print(solution.searchRange(nums2, target2)) # Output: [-1, -1]

# Example 3:
nums3 = []
target3 = 0
print(solution.searchRange(nums3, target3)) # Output: [-1, -1]
```

This code defines a `Solution` class with a `searchRange` method to find the starting and ending positions of the target value in the given array. The example usage demonstrates how to create an instance of the `Solution` class and call the `searchRange` method with different inputs.
104 changes: 104 additions & 0 deletions g0001_0100/s0035_search_insert_position/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
35\. Search Insert Position

Easy

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.

**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

**Example 4:**

**Input:** nums = [1,3,5,6], target = 0

**Output:** 0

**Example 5:**

**Input:** nums = [1], target = 0

**Output:** 0

**Constraints:**

* <code>1 <= nums.length <= 10<sup>4</sup></code>
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
* `nums` contains **distinct** values sorted in **ascending** order.
* <code>-10<sup>4</sup> <= target <= 10<sup>4</sup></code>

To solve this problem efficiently with a runtime complexity of O(log n), we can use binary search to find the insertion position of the target value in the sorted array. Here are the steps:

### Approach:

1. **Binary Search:**
- Implement binary search to find the insertion position of the target value.
- If the target value is found, return its index.
- If the target value is not found, binary search will determine the index where the target would be inserted to maintain the sorted order.

### Python Code:

```python
class Solution:
def searchInsert(self, nums, target):
left, right = 0, len(nums) - 1

while left <= right:
mid = (left + right) // 2

if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1

# If the target is not found, return the insertion position (left).
return left

# Example Usage:
solution = Solution()

# Example 1:
nums1 = [1, 3, 5, 6]
target1 = 5
print(solution.searchInsert(nums1, target1)) # Output: 2

# Example 2:
nums2 = [1, 3, 5, 6]
target2 = 2
print(solution.searchInsert(nums2, target2)) # Output: 1

# Example 3:
nums3 = [1, 3, 5, 6]
target3 = 7
print(solution.searchInsert(nums3, target3)) # Output: 4

# Example 4:
nums4 = [1, 3, 5, 6]
target4 = 0
print(solution.searchInsert(nums4, target4)) # Output: 0

# Example 5:
nums5 = [1]
target5 = 0
print(solution.searchInsert(nums5, target5)) # Output: 0
```

This code defines a `Solution` class with a `searchInsert` method to find the insertion position of the target value in the given sorted array. The example usage demonstrates how to create an instance of the `Solution` class and call the `searchInsert` method with different inputs.
104 changes: 104 additions & 0 deletions g0001_0100/s0039_combination_sum/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
39\. Combination Sum

Medium

Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.

The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is **guaranteed** that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.

**Example 1:**

**Input:** candidates = [2,3,6,7], target = 7

**Output:** [[2,2,3],[7]]

**Explanation:**

2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

**Example 2:**

**Input:** candidates = [2,3,5], target = 8

**Output:** [[2,2,2,2],[2,3,3],[3,5]]

**Example 3:**

**Input:** candidates = [2], target = 1

**Output:** []

**Example 4:**

**Input:** candidates = [1], target = 1

**Output:** [[1]]

**Example 5:**

**Input:** candidates = [1], target = 2

**Output:** [[1,1]]

**Constraints:**

* `1 <= candidates.length <= 30`
* `1 <= candidates[i] <= 200`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 500`

To solve the Combination Sum problem, you can use backtracking. Here are the steps you can follow:

1. **Define the function**: Create a function, let's name it `combinationSum`, that takes `candidates`, `target`, and any other necessary parameters.

2. **Sort the candidates**: Sort the `candidates` array. Sorting helps in pruning the search space during backtracking.

3. **Initialize variables**: Initialize an empty list to store the result combinations.

4. **Define a helper function**: Create a recursive helper function, let's name it `backtrack`, that takes the current combination, the current index of the candidate being considered, and the remaining target.

5. **Base case**: If the target is 0, add the current combination to the result list.

6. **Iterate through candidates**: Start iterating from the current index to the end of the `candidates` array.

7. **Check the sum condition**: For each candidate, check if adding it to the current combination keeps the sum less than or equal to the target. If so, recursively call the `backtrack` function with the updated combination, the current index, and the reduced target.

8. **Backtrack**: After the recursive call returns, remove the last element from the current combination to backtrack.

9. **Call the helper function**: Call the `backtrack` function initially with an empty combination, starting index 0, and the target.

10. **Return the result**: Return the list of combinations obtained.

Here's a Python code snippet implementing the above steps:

```python
class Solution:
def combinationSum(self, candidates, target):
def backtrack(start, target, path):
if target == 0:
result.append(path)
return
for i in range(start, len(candidates)):
if candidates[i] > target:
break
backtrack(i, target - candidates[i], path + [candidates[i]])

result = []
candidates.sort()
backtrack(0, target, [])
return result

# Test cases
solution = Solution()
print(solution.combinationSum([2,3,6,7], 7)) # Output: [[2, 2, 3], [7]]
print(solution.combinationSum([2,3,5], 8)) # Output: [[2, 2, 2, 2], [2, 3, 3], [5, 3]]
print(solution.combinationSum([2], 1)) # Output: []
print(solution.combinationSum([1], 1)) # Output: [[1]]
print(solution.combinationSum([1], 2)) # Output: [[1, 1]]
```

This implementation efficiently finds all unique combinations that sum up to the target.
Loading