Skip to content

Commit

Permalink
major rewrite; optimal solution
Browse files Browse the repository at this point in the history
  • Loading branch information
harishvc committed Oct 18, 2016
1 parent 2f66a9b commit a1b3900
Showing 1 changed file with 23 additions and 47 deletions.
70 changes: 23 additions & 47 deletions reverse-sentance.py
@@ -1,55 +1,31 @@
#Question: Reverse all words in a sentance
#Complexity: O(n) where n is the lenght of the sentance

#Answer

#Source: http://stackoverflow.com/questions/18686860/reverse-a-string-in-python-without-using-reversed-or-1
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]

sentances = ['Alice likes Bob']


#Solution 1: Using list comprehension
for n in sentances:
print (n,"===>",end=" ")
print (''.join([x for r in reverse(n).split(" ") for x in reverse(r) + " " ]))

#Solution 2: Function call (more space efficient than solution 1)
for n in sentances:
print (n, "===>",end=" ")
for x in reverse(n).split(" "):
print(reverse(x),end=" ")
print(" ")


#Solution 3: Convert string to list and then reverse
#Helper function that reverses all the characters between a start and end index (inclusive)
def reverse(a,start,end):
while start < end:
a[start],a[end] = a[end],a[start]
a[start], a[end] = a[end], a[start]
start += 1
end -= 1
return a

#Reference: https://www.interviewcake.com/question/python/reverse-words
#Time & Space complexity: O(n)
#Time complexity: O(n)
#Space Complexity: O(1)
def reverseSentance(a):
#step 1: convert string to list since string is immutable :notes:
na = list(a) #new a
size = len(na) -1
#step 2: reverse entire list
na = reverse(na,0,size)
#step 3: reverse each word (when space is encountered)
start = 0
for i in range(0,size+1):
if na[i] == " ":
reverse(na,start,i-1)
start = i + 1
elif i == size: #last word
reverse(na,start,i)
return "".join(na) #convert list back to string

a= "Alice likes Bob"
print(a, "===>", reverseSentance(a))
#step 1: reverse the entire string
reverse(a,0,len(a)-1)

#step 2: reverse each word in the string
start_index = 0
end_index = 0
for i in range(0,len(a)):
if a[i] == " ": #nd of word!
end_index = i-1 #leave the space
reverse(a,start_index,end_index)
start_index = i+1 #next character!
#IMPORTANT: Handle last word!
reverse(a,start_index,len(a)-1)


a= ['A','l','i','c','e'," ",'l','i','k','e','s'," ",'B','o','b']
print(a)
reverseSentance(a)
print(a)

0 comments on commit a1b3900

Please sign in to comment.