Skip to content

Commit 8385b62

Browse files
authored
Merge pull request BeeBombshell#112 from Rac-Ro007/main
Exponential Search and Three-Sum Dynamic Programming solution
2 parents de342de + 1071db2 commit 8385b62

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

DSA/three_sum.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Three Sum dynamic problem solution
2+
def threeSum(self, nums: List[int]) -> List[List[int]]:
3+
res = []
4+
nums.sort()
5+
6+
for i, num1 in enumerate(nums):
7+
8+
if i > 0 and num1 == nums[i-1]:
9+
continue
10+
11+
start, end = i+1, len(nums) - 1
12+
13+
while start < end:
14+
sum = num1 + nums[start] + nums[end]
15+
16+
if sum > 0:
17+
end -= 1
18+
elif sum < 0:
19+
start += 1
20+
else:
21+
res.append([num1, nums[start], nums[end]])
22+
start += 1
23+
while nums[start] == nums[start-1] and start < end:
24+
start += 1
25+
26+
return res
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<h1>Exponential Search</h1>
2+
3+
<h4>
4+
Exponential search is also known as doubling or galloping search. This mechanism is used to find the range where the search key may present. If L and U are the upper and lower bound of the list, then L and U both are the power of 2. For the last section, the U is the last position of the list. For that reason, it is known as exponential.
5+
</h4>
6+
<br>
7+
<h3> Complexity of Exponential Search Technique </h3>
8+
<hr>
9+
10+
<h4>
11+
Time Complexity: O(1) for the best case. O(log2 i) for average or worst case. Where i is the location where search key is present.
12+
<br>
13+
Space Complexity: O(1)
14+
</h4>
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Exponential Search
2+
def binary_search(arr, low, high, x):
3+
while low <= high:
4+
mid = low + (high - low)/2;
5+
6+
if arr[mid] == x:
7+
return mid
8+
elif arr[mid] < x:
9+
low = mid + 1
10+
else:
11+
high = mid - 1
12+
13+
return -1
14+
15+
def exponential_search(arr, low, high, x):
16+
if arr[low] == x:
17+
return low
18+
19+
i = (low + 1) * 2
20+
while i <= high and arr[i] <= x:
21+
i *= 2
22+
23+
return binary_search(arr, i / 2, min(i, high), x)
24+
25+
# arr = range(0,500)
26+
# x = 42
27+
# print(exponential_search(arr, 0, len(arr), x))

0 commit comments

Comments
 (0)