⌘K
Flycodx

Longest Palindromic Substring

Longest Palindromic Substring

MediumStrings0% accepted

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

Input format — only if your code reads from stdin

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

Approach

Expand-around-center: for each character (and each pair of adjacent characters), expand outward while left and right characters match. Track the longest window found. O(n²) time, O(1) space. Cover both odd-length (single center) and even-length (pair center) 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