← PayPal bank

PayPal · Question 17 · Strings

Longest Palindromic Substring

StringsJavacode⏱ O(n^2)💾 O(1)
Product-based

Problem

Find the longest palindromic substring in a given string.

Approach

Expand around center for each character.

Time O(n^2)Space O(1)

How it works

  1. 1Try odd and even centers everywhere.
  2. 2Expand while characters mirror; keep the longest.

Sample input / output

Input:
s = "cbbd"
Output:
bb

Constraints

1 <= s.length <= 1000.

Solution — read it, then walk it

Time O(n^2)Space O(1)Loops 2Branches 2Returns 2source · Java
Scroll sideways for wide charts — the view follows the active step.
yes↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static StringlongestPalindrome(String s)if (s == null ||s.length() < 1) return""DEFINE start = 0, end = 0for (int i = 0; i <s.length(); i++)DEFINE len1 =expandAroundCenter(s, i, i)DEFINE len2 =expandAroundCenter(s, i, i+ 1)DEFINE len = Math.max(len1,len2)if (len > end - start)start = i - (len - 1) / 2end = i + len / 2RETURN s.substring(start,end + 1)DEFINE static intexpandAroundCenter(Strings, int left, int right)while (left >= 0 &&right < s.length() &&s.charAt(left) =…left--right++RETURN right - left - 1DEFINE static voidmain(String[] args)System.out.println(longestPalindrome("cbbd"))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits