Skip to content

Commit 65cdd69

Browse files
committed
Lesson 2 arrays
1 parent 00ae7f9 commit 65cdd69

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

02_cyclic_rotation.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/"""
2+
3+
# Time complexity:
4+
# Slice array into two parts and concatenate them, each taking O(N) time per op
5+
# Overall = O(N)
6+
7+
def solution(a: list[int], k: int) -> list[int]:
8+
"""Rotate array A to the right K times."""
9+
n = len(a)
10+
if n == 0:
11+
return a
12+
k = k % n # if K is greater than N
13+
return a[-k:] + a[:-k]

02_odd_occurrences_in_array.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/"""
2+
3+
# Time complexity:
4+
# Single pass through array, O(N)
5+
# XOR operation is O(log M) where M is the max value,
6+
# but M <= 1,000,000,000 is effectively constant (fits in 32/64 bits)
7+
# Overall = O(N)
8+
9+
def solution(a: list[int]) -> int:
10+
"""Find the value that occurs in odd number of elements."""
11+
result = 0
12+
# XOR is commutative, associative and self-inverse.
13+
# All pairs cancel, leaving the odd occurring number
14+
for number in a:
15+
result ^= number
16+
return result

0 commit comments

Comments
 (0)