Reversing a string in place

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non tortor a turpis fermentum porta.

1
2
3
4
5
6
def reverse_in_place(chars):
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1

Palindromes

A palindrome reads the same forwards and backwards. Use two pointers from both ends and compare as you walk inward.

1
2
3
4
5
6
7
8
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

Don’t forget to mark this chapter complete when you’re done.

Saved locally to your browser.