-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreverse_string_in_array.py
More file actions
31 lines (24 loc) · 884 Bytes
/
reverse_string_in_array.py
File metadata and controls
31 lines (24 loc) · 884 Bytes
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
"""
Reverse string in an array in constant space and in constant time
"""
#Leetcode: https://leetcode.com/problems/reverse-string/
def reverseString(s):
#using a recursive function
# time is O(N), space is O(N)
def helper(left, right):
if left < right:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
helper(left, right)
helper(0, len(s) - 1)
return s
def reverse_string(s):
#using 2 pointer approach to slide through
#time is O(N), space is O(1)
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left, right = left + 1, right - 1
return s
print("Using recursive approach gives: ", reverseString(['h','e','l','l','o']))
print("Using 2 pointer approach to slide across gives: ", reverse_string(['h','e','l','l','o']))