← L&T Mindtree bank

L&T Mindtree · Question 15 · Strings

Longest Palindromic Substring

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

Problem

You are given a string. Find the longest palindromic substring.

Approach

Expand around every center and keep the longest palindrome.

Time O(n²)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 = "forgeeksskeegfor"
Output:
geeksskeeg

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.
yesnoyes↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static StringlongestPalindrome(String s)DEFINE start = 0, maxLen =0for (int i = 0; i <s.length(); i++)DEFINE [] r1 = expand(s, i,i)DEFINE [] r2 = expand(s, i,i + 1)if (r1[1] - r1[0] + 1> maxLen)start = r1[0]maxLen = r1[1] - r1[0] + 1if (r2[1] - r2[0] + 1> maxLen)start = r2[0]maxLen = r2[1] - r2[0] + 1RETURN s.substring(start,start + maxLen)DEFINE static int[]expand(String s, int left,int right)while (left >= 0 &&right < s.length() &&s.charAt(left) =…left--right++RETURN new int[]{left + 1,right - 1}DEFINE static voidmain(String[] args)System.out.println(longestPalindrome("forgeeksskeegfor"))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

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