← Microsoft bank

Microsoft · Question 9 · Strings

Longest Palindromic Substring

StringsJavacode⏱ O(n²)💾 O(1)
Product-based

Problem

Given a string s, return the longest palindromic substring.

Approach

Expand around every center and keep the longest span.

Time O(n²)Space O(1)

How it works

  1. 1Try odd and even centers everywhere.
  2. 2Expand while characters mirror.
  3. 3Remember the longest span.

Sample input / output

Input:
babad
Output:
aba

Constraints

1 <= s.length <= 1000.

Solution — read it, then walk it

Time O(n²)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)java.util.Scanner sc = newjava.util.Scanner(System.in)String s = sc.next()System.out.println(longestPalindrome(s))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

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