SECTION 16 / 24

Is a word a palindrome?

1 min read
madam reduces to ada and then d after matching and removing both ends. One remaining character is accepted.
madam reduces to ada and then d after matching and removing both ends. One remaining character is accepted.
REAL COURSE DATA · BUILD AND UNPACK LISTS

Compare both ends of a word

Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change, then step through the list. The original course records remain unchanged.

L = explode(lowercase(Word))
while length(L) >= 2:
    if first(L) != last(L):
        return false
    L = init(rest(L))
return true

A palindrome reads the same forwards and backwards. If the first and last characters differ, reject immediately. If they agree, remove BOTH and test the shorter middle. For madam, compare m/m, then a/a, leaving d. For noon, compare n/n, then o/o, leaving an empty list.

The guard ensures init(rest(L)) is applied while at least two characters are available. Zero or one remaining character has no mismatched endpoints, so returns true. Here we lowercase before comparing; otherwise Madam and madam would differ in a literal case-sensitive test. We do not remove punctuation or spaces in this demonstration.

The loop shrinks by two characters on every successful step. That is its progress argument. Shrinking by one would perform a different algorithm; failing to update L would repeat the same comparison forever.

Try it yourself

Why is one matching endpoint pair not enough?

Show explained answer

The interior may still fail. abca has equal outer a characters, but the remaining b and c do not match.

Try it yourself

How many endpoint comparisons does madam need?

Show explained answer

Two: m with m, then a with a. The final single d requires no comparison.

Try it yourself

What does this algorithm return for an empty input?

Show explained answer

True under the stated sequence convention: there are no unequal mirrored positions. The loop never runs.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑