Skip to content

Commit 868f016

Browse files
authored
Added tasks 34-51
1 parent f927e39 commit 868f016

File tree

10 files changed

+946
-0
lines changed

10 files changed

+946
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
34\. Find First and Last Position of Element in Sorted Array
2+
3+
Medium
4+
5+
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
6+
7+
If `target` is not found in the array, return `[-1, -1]`.
8+
9+
You must write an algorithm with `O(log n)` runtime complexity.
10+
11+
**Example 1:**
12+
13+
**Input:** nums = [5,7,7,8,8,10], target = 8
14+
15+
**Output:** [3,4]
16+
17+
**Example 2:**
18+
19+
**Input:** nums = [5,7,7,8,8,10], target = 6
20+
21+
**Output:** [-1,-1]
22+
23+
**Example 3:**
24+
25+
**Input:** nums = [], target = 0
26+
27+
**Output:** [-1,-1]
28+
29+
**Constraints:**
30+
31+
* <code>0 <= nums.length <= 10<sup>5</sup></code>
32+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
33+
* `nums` is a non-decreasing array.
34+
* <code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code>
35+
36+
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:
37+
38+
### Approach:
39+
40+
1. **Binary Search for Starting Position:**
41+
- Use binary search to find the starting position of the target value.
42+
- When the target value is found, continue searching towards the left to find the leftmost occurrence.
43+
- Update the left boundary to narrow down the search space.
44+
45+
2. **Binary Search for Ending Position:**
46+
- Use binary search to find the ending position of the target value.
47+
- When the target value is found, continue searching towards the right to find the rightmost occurrence.
48+
- Update the right boundary to narrow down the search space.
49+
50+
3. **Handle Missing Target:**
51+
- If the target value is not found, return [-1, -1].
52+
53+
### Python Code:
54+
55+
```python
56+
class Solution:
57+
def searchRange(self, nums, target):
58+
def search_boundary(nums, target, is_left):
59+
left, right = 0, len(nums) - 1
60+
boundary = -1
61+
62+
while left <= right:
63+
mid = (left + right) // 2
64+
65+
if nums[mid] == target:
66+
boundary = mid
67+
if is_left:
68+
right = mid - 1
69+
else:
70+
left = mid + 1
71+
elif nums[mid] < target:
72+
left = mid + 1
73+
else:
74+
right = mid - 1
75+
76+
return boundary
77+
78+
left_boundary = search_boundary(nums, target, is_left=True)
79+
right_boundary = search_boundary(nums, target, is_left=False)
80+
81+
return [left_boundary, right_boundary]
82+
83+
# Example Usage:
84+
solution = Solution()
85+
86+
# Example 1:
87+
nums1 = [5, 7, 7, 8, 8, 10]
88+
target1 = 8
89+
print(solution.searchRange(nums1, target1)) # Output: [3, 4]
90+
91+
# Example 2:
92+
nums2 = [5, 7, 7, 8, 8, 10]
93+
target2 = 6
94+
print(solution.searchRange(nums2, target2)) # Output: [-1, -1]
95+
96+
# Example 3:
97+
nums3 = []
98+
target3 = 0
99+
print(solution.searchRange(nums3, target3)) # Output: [-1, -1]
100+
```
101+
102+
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.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
35\. Search Insert Position
2+
3+
Easy
4+
5+
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.
6+
7+
You must write an algorithm with `O(log n)` runtime complexity.
8+
9+
**Example 1:**
10+
11+
**Input:** nums = [1,3,5,6], target = 5
12+
13+
**Output:** 2
14+
15+
**Example 2:**
16+
17+
**Input:** nums = [1,3,5,6], target = 2
18+
19+
**Output:** 1
20+
21+
**Example 3:**
22+
23+
**Input:** nums = [1,3,5,6], target = 7
24+
25+
**Output:** 4
26+
27+
**Example 4:**
28+
29+
**Input:** nums = [1,3,5,6], target = 0
30+
31+
**Output:** 0
32+
33+
**Example 5:**
34+
35+
**Input:** nums = [1], target = 0
36+
37+
**Output:** 0
38+
39+
**Constraints:**
40+
41+
* <code>1 <= nums.length <= 10<sup>4</sup></code>
42+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
43+
* `nums` contains **distinct** values sorted in **ascending** order.
44+
* <code>-10<sup>4</sup> <= target <= 10<sup>4</sup></code>
45+
46+
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:
47+
48+
### Approach:
49+
50+
1. **Binary Search:**
51+
- Implement binary search to find the insertion position of the target value.
52+
- If the target value is found, return its index.
53+
- If the target value is not found, binary search will determine the index where the target would be inserted to maintain the sorted order.
54+
55+
### Python Code:
56+
57+
```python
58+
class Solution:
59+
def searchInsert(self, nums, target):
60+
left, right = 0, len(nums) - 1
61+
62+
while left <= right:
63+
mid = (left + right) // 2
64+
65+
if nums[mid] == target:
66+
return mid
67+
elif nums[mid] < target:
68+
left = mid + 1
69+
else:
70+
right = mid - 1
71+
72+
# If the target is not found, return the insertion position (left).
73+
return left
74+
75+
# Example Usage:
76+
solution = Solution()
77+
78+
# Example 1:
79+
nums1 = [1, 3, 5, 6]
80+
target1 = 5
81+
print(solution.searchInsert(nums1, target1)) # Output: 2
82+
83+
# Example 2:
84+
nums2 = [1, 3, 5, 6]
85+
target2 = 2
86+
print(solution.searchInsert(nums2, target2)) # Output: 1
87+
88+
# Example 3:
89+
nums3 = [1, 3, 5, 6]
90+
target3 = 7
91+
print(solution.searchInsert(nums3, target3)) # Output: 4
92+
93+
# Example 4:
94+
nums4 = [1, 3, 5, 6]
95+
target4 = 0
96+
print(solution.searchInsert(nums4, target4)) # Output: 0
97+
98+
# Example 5:
99+
nums5 = [1]
100+
target5 = 0
101+
print(solution.searchInsert(nums5, target5)) # Output: 0
102+
```
103+
104+
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.
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
39\. Combination Sum
2+
3+
Medium
4+
5+
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**.
6+
7+
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.
8+
9+
It is **guaranteed** that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
10+
11+
**Example 1:**
12+
13+
**Input:** candidates = [2,3,6,7], target = 7
14+
15+
**Output:** [[2,2,3],[7]]
16+
17+
**Explanation:**
18+
19+
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
20+
7 is a candidate, and 7 = 7.
21+
These are the only two combinations.
22+
23+
**Example 2:**
24+
25+
**Input:** candidates = [2,3,5], target = 8
26+
27+
**Output:** [[2,2,2,2],[2,3,3],[3,5]]
28+
29+
**Example 3:**
30+
31+
**Input:** candidates = [2], target = 1
32+
33+
**Output:** []
34+
35+
**Example 4:**
36+
37+
**Input:** candidates = [1], target = 1
38+
39+
**Output:** [[1]]
40+
41+
**Example 5:**
42+
43+
**Input:** candidates = [1], target = 2
44+
45+
**Output:** [[1,1]]
46+
47+
**Constraints:**
48+
49+
* `1 <= candidates.length <= 30`
50+
* `1 <= candidates[i] <= 200`
51+
* All elements of `candidates` are **distinct**.
52+
* `1 <= target <= 500`
53+
54+
To solve the Combination Sum problem, you can use backtracking. Here are the steps you can follow:
55+
56+
1. **Define the function**: Create a function, let's name it `combinationSum`, that takes `candidates`, `target`, and any other necessary parameters.
57+
58+
2. **Sort the candidates**: Sort the `candidates` array. Sorting helps in pruning the search space during backtracking.
59+
60+
3. **Initialize variables**: Initialize an empty list to store the result combinations.
61+
62+
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.
63+
64+
5. **Base case**: If the target is 0, add the current combination to the result list.
65+
66+
6. **Iterate through candidates**: Start iterating from the current index to the end of the `candidates` array.
67+
68+
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.
69+
70+
8. **Backtrack**: After the recursive call returns, remove the last element from the current combination to backtrack.
71+
72+
9. **Call the helper function**: Call the `backtrack` function initially with an empty combination, starting index 0, and the target.
73+
74+
10. **Return the result**: Return the list of combinations obtained.
75+
76+
Here's a Python code snippet implementing the above steps:
77+
78+
```python
79+
class Solution:
80+
def combinationSum(self, candidates, target):
81+
def backtrack(start, target, path):
82+
if target == 0:
83+
result.append(path)
84+
return
85+
for i in range(start, len(candidates)):
86+
if candidates[i] > target:
87+
break
88+
backtrack(i, target - candidates[i], path + [candidates[i]])
89+
90+
result = []
91+
candidates.sort()
92+
backtrack(0, target, [])
93+
return result
94+
95+
# Test cases
96+
solution = Solution()
97+
print(solution.combinationSum([2,3,6,7], 7)) # Output: [[2, 2, 3], [7]]
98+
print(solution.combinationSum([2,3,5], 8)) # Output: [[2, 2, 2, 2], [2, 3, 3], [5, 3]]
99+
print(solution.combinationSum([2], 1)) # Output: []
100+
print(solution.combinationSum([1], 1)) # Output: [[1]]
101+
print(solution.combinationSum([1], 2)) # Output: [[1, 1]]
102+
```
103+
104+
This implementation efficiently finds all unique combinations that sum up to the target.

0 commit comments

Comments
 (0)