Skip to content

Commit 270e68e

Browse files
committed
Added twosum and inversion count
1 parent 8590555 commit 270e68e

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def inversion_count(arr):
2+
print(arr)
3+
i = 0
4+
j = len(arr) - 1
5+
total = 0
6+
while i <= j:
7+
if arr[i] > arr[j]:
8+
print((arr[i], arr[j]))
9+
total += 1
10+
j -= 1
11+
else:
12+
j = len(arr) - 1
13+
i += 1
14+
return total
15+
16+
17+
def number_of_inversions(arr):
18+
if len(arr) <= 1:
19+
return 0
20+
return number_of_inversions(arr[:len(arr) // 2]) + number_of_inversions(arr[len(arr) // 2:]) + inversion_count(arr)
21+
22+
23+
if __name__ == '__main__':
24+
glob_arr = [2, 3, 8, 6, 1]
25+
print(number_of_inversions(glob_arr))

pythonProblems/clrs/twosum.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
4+
def two_sum(a: List[int], x):
5+
"""
6+
O(n lg n) implementation of two-sum
7+
8+
Args:
9+
a (List[int]): _description_
10+
x (_type_): _description_
11+
12+
Returns:
13+
_type_: _description_
14+
"""
15+
a = sorted(a)
16+
i = len(a) - 1
17+
j = 0
18+
while i != j and j < i:
19+
if a[i] + a[j] < x:
20+
j += 1
21+
elif a[i] + a[j] > x:
22+
i -= 1
23+
else:
24+
print(a[i], a[j])
25+
return True
26+
return False
27+
28+
29+
if __name__ == '__main__':
30+
arr = [1, 5, 4, 10, 2, 3]
31+
_sum = 11
32+
print(two_sum(arr, _sum))

0 commit comments

Comments
 (0)