Merge pull request #310 from Sankalp7943/sankalp/arrays

chore(Python): add sankalp arrays
pull/313/head
Venkata Sridhar Sai 2021-05-17 20:03:42 +05:30 committed by GitHub
commit abe0910350
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 70 additions and 0 deletions

View File

@ -2,6 +2,9 @@
## Arrays ## Arrays
1. [Count Inversions](arrays/counting_inversions.py) 1. [Count Inversions](arrays/counting_inversions.py)
2. [Majority Element](arrays/majority_element.py)
3. [Rotate Array](arrays/rotate_array.py)
4. [Missing Number](arrays/missing_number.py)
## Linked Lists ## Linked Lists
1. [Doubly](linked_lists/doubly.py) 1. [Doubly](linked_lists/doubly.py)

View File

@ -0,0 +1,26 @@
"""
Algorithm Type: Array Traversal
Time Complexity: O(n)
"""
numbers = [2, 2, 5, 6, 2, 6, 2, 10, 2]
def majority_element(numbers):
m = float("inf")
cnt = 0
for num in numbers:
if cnt == 0:
m = num
cnt += 1
elif m == num:
cnt += 1
else:
cnt -= 1
# to verify the most frequent number is greater than length of aaray//2
recheck_cnt = 0
for num in numbers:
if num == m:
recheck_cnt += 1
return m if recheck_cnt > len(numbers)//2 else None
if __name__ == "__main__":
print(majority_element(numbers))

View File

@ -0,0 +1,15 @@
"""
Algorithm Type: Array Traversal
Time Complexity: O(n)
"""
numbers = [1, 2, 4, 3, 6, 7, 9, 8, 10]
n = 10
def missing_number(numbers, n):
s = sum(numbers)
expected_s = (n*(n+1))//2 #for C++ or similar, keep in mind expected_s can overflow MAX INT limit.
return expected_s - s
if __name__ == "__main__":
print(missing_number(numbers, n))

View File

@ -0,0 +1,26 @@
"""
Algorithm Type: Array Traversal
Time Complexity: O(n)
"""
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
k = 3
def rotate_array(numbers, k):
n = len(numbers)
k = k % n
if k == 0:
return numbers
for i in range(n-k):
if i>((n-k)//2):
break
numbers[i], numbers[n-k-(i+1)] = numbers[n-k-(i+1)], numbers[i]
for i in range(k):
if i>k//2:
break
numbers[-1-i], numbers[-k+i] = numbers[-k+i], numbers[-1-i]
reversed_numbers = numbers[::-1]
return reversed_numbers
if __name__ == "__main__":
print(rotate_array(numbers, k))