Goldman Sachs coderpad question

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2022-05-03Added By Anonymous
Source: Link

CoderPad question of Goldman Sachs - 29th April 2022

Interviewer was very helpful, and question was also of easy level.


Q. Return the start index and length of the longest substring having identical characters in a given String.

i/p : S = "aabbbbbccddb"

o/p: [2,5]

explaination : As longest substring is 'bbbbb' of length 5 and start index as 2


i/p: S = "aabbb22rrrrr345571111111"

o/p: [17,7]

explaination : As '1111111' is the longest substring of length 7 and start index =17


I used sliding window to solve this. Please comment for the solution.

1public class GSLongestSubString { 2 public static void main(String[] args){ 3 String s1 = "aabbbbbccddb"; 4 String s2 = "aabbb22rrrrr345571111111"; 5 String s3 = "aaaabbeedddd"; 6 System.out.println("\n----------------"+"For Given String: "+s1+"----------------"); 7 callLongestSubstring(s1); 8 System.out.println("\n----------------"+"For Given String: "+s2+"----------------"); 9 callLongestSubstring(s2); 10 System.out.println("\n----------------"+"For Given String: "+s3+"----------------"); 11 callLongestSubstring(s3); 12 } 13 public static void callLongestSubstring(String s){ 14 int maxLen=0,start=0,end=0,len=0,startIndex=0; 15 while(end+1!=s.length()){ 16 if(s.charAt(start)==s.charAt(end)) 17 { 18 end++; 19 len=end-start; 20 } 21 else 22 start=end; 23 if(maxLen<len) 24 { 25 if(end==s.length()-1) 26 maxLen=len+1; 27 else 28 maxLen=len; 29 startIndex=start; 30 } 31 System.out.println("start: "+start+" end: "+end+" len: "+len+" maxLen: "+ 32 maxLen+" startIndex: "+startIndex); 33 } 34 System.out.println("Start Index= "+startIndex+" Longest Length= "+maxLen); 35 } 36}
Comments