CodexBloom - Programming Q&A Platform

Issues with Implementing the Knuth-Morris-Pratt Algorithm in Java - Incorrect Pattern Matching Results on Overlapping Patterns

๐Ÿ‘€ Views: 17 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-08-08
algorithm pattern-matching kmp Java

I just started working with I need some guidance on I'm converting an old project and Quick question that's been bugging me - I'm currently implementing the Knuth-Morris-Pratt (KMP) algorithm in Java for pattern matching, but I'm facing issues where the algorithm returns incorrect results when the pattern has overlapping sequences..... Iโ€™ve been following the standard KMP approach, but it seems that my implementation is not handling cases like the pattern "ABAB" correctly in the text "ABABABAB". Hereโ€™s a snippet of my code for the KMP search function: ```java public class KMPAlgorithm { public static void KMPSearch(String text, String pattern) { int[] lps = computeLPSArray(pattern); int i = 0; // index for text int j = 0; // index for pattern while (i < text.length()) { if (pattern.charAt(j) == text.charAt(i)) { i++; j++; } if (j == pattern.length()) { System.out.println("Found pattern at index " + (i - j)); j = lps[j - 1]; } else if (i < text.length() && pattern.charAt(j) != text.charAt(i)) { if (j != 0) { j = lps[j - 1]; } else { i++; } } } } private static int[] computeLPSArray(String pattern) { int[] lps = new int[pattern.length()]; int length = 0; int i = 1; while (i < pattern.length()) { if (pattern.charAt(i) == pattern.charAt(length)) { length++; lps[i] = length; i++; } else { if (length != 0) { length = lps[length - 1]; } else { lps[i] = 0; i++; } } } return lps; } } ``` In my tests with the input string `"ABABABAB"` and the pattern `"ABAB"`, I'm expecting to find the pattern at indices 0, 2, and 4. However, the algorithm only returns the first match at index 0 and misses the others, leading to missed results. I've tried modifying the way I update the index `j`, but it doesnโ€™t seem to affect the outcome. I'm using Java 17 and running this in a standard console application. Any insights or suggestions for how to modify my implementation to handle overlapping patterns correctly would be greatly appreciated! I'm working on a service that needs to handle this. What's the best practice here? I've been using Java for about a year now. This issue appeared after updating to Java 3.9. Any suggestions would be helpful. Could this be a known issue?