STRG-P6

Palindromes in a string

Practice 6 of 6String algorithms11 tests

The problem

Return a pair (count, longest). count is the number of pieces s[a:b] (with a < b) that are palindromes; pieces with the same letters at different places count separately. longest is the longest palindromic piece; if there is a tie, the one that starts earliest.

palindromes("aaa")       # (6, "aaa")
palindromes("abba")      # (6, "abba")
palindromes("abaxcdc")   # (9, "aba")

The string has at least one lower-case letter.

Limits

  • Up to 200,000 letters. The big tests have 4 seconds each.
  • The count can be about 20 billion; growing each palindrome from its centre is too slow when there are that many.

Builds on STRG-6 Manacher’s palindromes.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1abacabaNot run
2A runNot run
3Even lengthNot run
4Nothing longer than a letterNot run
5One letterNot run
6A tieNot run
7Even winsNot run
8200,000 of one letterNot run
9A long alternating stringNot run
10Random lettersNot run
11The Fibonacci wordNot run