-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrays_ds.py
41 lines (36 loc) · 1.26 KB
/
arrays_ds.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python3
# Arrays - DS
#
# https://www.hackerrank.com/challenges/arrays-ds/problem
#
# Reverse an array of integers.
def test():
# specify approach
reverse_array = Solution().loop
# pytest
assert reverse_array([1,2,3,4,5]) == [5,4,3,2,1]
assert reverse_array([1,2,1]) == [1,2,1]
assert reverse_array([1,1,1]) == [1,1,1]
assert reverse_array([]) == []
class Solution:
"""
Approach: Using standard library `reverse()` function
Idea: Well, we're basically just cheating by using the std lib function
Time: O(n), must iterate through entire list at least once to "see" every element
Space: O(1), `reverse()` operates in-place
"""
def std_lib(self, arr: list[int]) -> list[int]:
arr.reverse()
return arr
"""
Approach: Swap elements in loop
Idea: Iterate through list while swapping elements with same distance from middle
Time: O(n), iterate only through half the list, but two operations per iteration
Space: O(1), operates in-place
"""
def loop(self, arr: list[int]) -> list[int]:
n = len(arr)
for i in range(n // 2):
# swap arr[i] and arr[n-i-1]
arr[i], arr[n-i-1] = arr[n-i-1], arr[i]
return arr