Levenshtein Distance
Java Programming
Search Optimization
String Matching
Algorithm Implementation

Improving search result using Levenshtein distance in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Levenshtein distance is a practical way to improve search when users misspell a word or type a close variant of the correct term. In Java, it is often used to rank suggestions, correct short queries, or reorder existing search results after a broader search step has already produced candidate matches.

What Levenshtein Distance Actually Gives You

Levenshtein distance measures how many single-character edits are needed to turn one string into another. The allowed edits are insertion, deletion, and substitution. A smaller distance means the strings are more similar.

For search, that means a query like javs can still rank java highly because the distance is only 1. The metric works especially well for product names, usernames, tags, and other short strings where spelling mistakes are common.

Here is a simple Java implementation:

java
1public static int levenshtein(String a, String b) {
2    int[][] dp = new int[a.length() + 1][b.length() + 1];
3
4    for (int i = 0; i <= a.length(); i++) {
5        dp[i][0] = i;
6    }
7
8    for (int j = 0; j <= b.length(); j++) {
9        dp[0][j] = j;
10    }
11
12    for (int i = 1; i <= a.length(); i++) {
13        for (int j = 1; j <= b.length(); j++) {
14            int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;
15
16            dp[i][j] = Math.min(
17                Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1),
18                dp[i - 1][j - 1] + cost
19            );
20        }
21    }
22
23    return dp[a.length()][b.length()];
24}

This is the classic dynamic-programming solution. It is easy to understand and accurate, though not always the fastest option for very large candidate sets.

Ranking Search Candidates

Levenshtein distance is usually not your primary search engine. A better approach is:

  1. Use a fast search index or prefix filter to gather candidate terms.
  2. Compute Levenshtein distance only for those candidates.
  3. Sort candidates by score.

Here is a small ranking example:

java
1import java.util.ArrayList;
2import java.util.Comparator;
3import java.util.List;
4
5public class SearchRanker {
6    public static void main(String[] args) {
7        String query = "javs";
8        List<String> candidates = List.of("java", "javascript", "kotlin", "scala");
9
10        List<String> ranked = new ArrayList<>(candidates);
11        ranked.sort(Comparator.comparingInt(term -> levenshtein(query, term)));
12
13        System.out.println(ranked);
14    }
15
16    public static int levenshtein(String a, String b) {
17        int[][] dp = new int[a.length() + 1][b.length() + 1];
18
19        for (int i = 0; i <= a.length(); i++) {
20            dp[i][0] = i;
21        }
22        for (int j = 0; j <= b.length(); j++) {
23            dp[0][j] = j;
24        }
25
26        for (int i = 1; i <= a.length(); i++) {
27            for (int j = 1; j <= b.length(); j++) {
28                int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;
29                dp[i][j] = Math.min(
30                    Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1),
31                    dp[i - 1][j - 1] + cost
32                );
33            }
34        }
35
36        return dp[a.length()][b.length()];
37    }
38}

In a real search system, you would combine this with other ranking signals such as popularity, exact-prefix matches, token overlap, or business relevance.

Normalize the Score for Better Results

Raw edit distance can mislead when string lengths differ a lot. A distance of 2 is small for a ten-character word but large for a three-character word. A normalized score often works better:

java
1public static double normalizedSimilarity(String a, String b) {
2    int distance = levenshtein(a, b);
3    int maxLength = Math.max(a.length(), b.length());
4    return maxLength == 0 ? 1.0 : 1.0 - ((double) distance / maxLength);
5}

This makes ranking fairer across short and long terms. It also lets you define thresholds, such as ignoring anything below 0.6 similarity.

Use Existing Libraries When Appropriate

For production code, you do not always need to maintain the algorithm yourself. Apache Commons Text provides a tested implementation:

java
1import org.apache.commons.text.similarity.LevenshteinDistance;
2
3LevenshteinDistance distance = new LevenshteinDistance();
4int score = distance.apply("javs", "java");
5System.out.println(score);

That is often preferable unless you need a custom variant or a highly optimized implementation.

Common Pitfalls

  • Applying Levenshtein distance to every document in a large corpus is too expensive. Narrow the candidate set first.
  • Using raw distance without length normalization can rank short strings unfairly.
  • Treating character-level similarity as the only signal often hurts search quality for multi-word queries.
  • Ignoring case folding, accent normalization, or token cleanup reduces match quality before the algorithm even runs.
  • Over-correcting queries can frustrate users when exact but uncommon terms are replaced by more popular near matches.

Summary

  • Levenshtein distance is useful for typo tolerance and suggestion ranking in Java search features.
  • Use it after a first-pass candidate search, not as the only retrieval step.
  • Normalize scores so comparisons stay meaningful across different string lengths.
  • Combine edit distance with exact matches and other ranking signals for better results.
  • Prefer a tested library implementation unless you need custom behavior or tighter control.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.