This notebook was prepared by Donne Martin. Source and license info is on GitHub.

Challenge Notebook

Problem: Implement a function to reverse a string (a list of characters), in-place.


  • Can we assume the string is ASCII?
    • Yes
    • Note: Unicode strings could require special handling depending on your language
  • Since we need to do this in-place, it seems we cannot use the slice operator or the reversed function?
    • Correct
  • Since Python string are immutable, can we use a list of characters instead?
    • Yes

Test Cases

  • None -> None
  • [''] -> ['']
  • ['f', 'o', 'o', ' ', 'b', 'a', 'r'] -> ['r', 'a', 'b', ' ', 'o', 'o', 'f']


Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.


In [ ]:
class ReverseString(object):

    def reverse(self, chars):
        # TODO: Implement me

Unit Test

The following unit test is expected to fail until you solve the challenge.

In [ ]:
# %load
import unittest

class TestReverse(unittest.TestCase):

    def test_reverse(self, func):
        self.assertEqual(func(None), None)
        self.assertEqual(func(['']), [''])
            ['f', 'o', 'o', ' ', 'b', 'a', 'r']),
            ['r', 'a', 'b', ' ', 'o', 'o', 'f'])
        print('Success: test_reverse')

    def test_reverse_inplace(self, func):
        target_list = ['f', 'o', 'o', ' ', 'b', 'a', 'r']
        self.assertEqual(target_list, ['r', 'a', 'b', ' ', 'o', 'o', 'f'])
        print('Success: test_reverse_inplace')

def main():
    test = TestReverse()
    reverse_string = ReverseString()

if __name__ == '__main__':

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.