Search code examples
pythonstringin-place

Why this Python solution is not in-place solution?


I was asked this question in one of the interviews. I got feedback from the recruiter saying I didn't solve this problem in place. I was wondering why this solution is not in place? What did I miss here?

Input is the character list like ['h','o','w',' ','a','r','e',' ','y','o','u','?']. The output should be a string like ?you are how.

charArr = ['h','o','w',' ','a','r','e',' ','y','o','u','?']
#output = ?you are how
class Solution():
    def reverseStr(self,charArr):
        charArr = ''.join(charArr).split()[::-1]
        for i in range(len(charArr)):
            if not charArr[i][-1].isalnum():
                charArr[i] = charArr[i][-1] + charArr[i][:-1]
        print ' '.join(charArr)
s1 = Solution()
s1.reverseStr(charArr)

Solution

  • An in-place solution will never assign a new value to the list that is passed as argument, because if you do that the value of the list that was passed by the caller will not have changed after the call.

    You could see that when doing a print(charArr) after the code you posted: it will just print the original list.

    You can use the reverse() method to reverse the values in a list. Also the syntax list[start:end] = ... can be used to mutate a list in-place.

    Here is a way you could solve the challenge correctly:

    def reverseStr(charArr):
        charArr.reverse() # this is in-place
        start = 0
        for end in range(1, len(charArr)+1):
            if end >= len(charArr) or charArr[end].isalnum() != charArr[end-1].isalnum():
                charArr[start:end] = charArr[start:end][::-1] # in-place reversal of word
                start = end
    
    charArr = ['h','o','w',' ','a','r','e',' ','y','o','u','?']
    reverseStr(charArr)
    print (charArr) # important to test that charArr changed == proof of "in-place"