⌘K
Flycodx

Longest Palindromic Substring

Longest Palindromic Substring

MediumStrings100% accepted

Given a string s, find and return the longest substring that reads the same forward and backward (a palindrome). A substring is a contiguous sequence of characters within the string. If there are multiple palindromic substrings of the same maximum length, return the one that appears first (leftmost). Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: "babad" → "bab" (both "bab" and "aba" are valid; return first)

Input format — only if your code reads from stdin

Input format (stdin): - A single string s (no spaces) Output: the longest palindromic substring.

Approach

For each character (and each pair of adjacent characters), expand outward while the left and right characters match. Track the longest valid window found. This covers both odd-length and even-length palindromes.

Input

babad

Output

bab
  • •1 ≤ len(s) ≤ 1000, s contains only lowercase English letters
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3