Question
Given two strings, write a function that returns the longest common substring.
eg.
longestSubstring("ABAB", "BABA") = "ABA"
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public String longestSubstring(String a, String b) { String out = ""; if (a.length() == 0 || b.length == 0) return out; int len = 0; int[][] cache = new int[a.length()][b.length()]; for (int i = 0; i < a.length(); i++) { for (int j = 0; j < b.length(); j++) { if (a.charAt(i) == b.charAt(j)) { if (i == 0 || j == 0) { cache[i][j] = 1; } else { cache[i][j] = cache[i-1][j-1] + 1; } if (cache[i][j] > len) { len = cache[i][j]; out = a.substring(i - len + 1, i+1); } } } } return out; } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.