Problem solution · Java

Find the Shortest Superstring

Find the Shortest Superstring: a Java solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
69 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Find the Shortest Superstring, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 69 lines of Java from the credited upstream file 943.java.
  • The implementation visibly relies on sequence storage.
  • 6 loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFind the Shortest Superstring · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public String shortestSuperstring(String[] words) {    final int n = words.length;    // cost[i][j] := the cost to append words[j] after words[i]    int[][] cost = new int[n][n];     // Pre-calculate cost array to save time.    for (int i = 0; i < n; ++i)      for (int j = i + 1; j < n; ++j) {        cost[i][j] = getCost(words[i], words[j]);        cost[j][i] = getCost(words[j], words[i]);      }     List<Integer> path = new ArrayList<>();    List<Integer> bestPath = new ArrayList<>();     minLength = n * 20; // given by problem     dfs(words, cost, path, bestPath, 0, 0, 0);     StringBuilder sb = new StringBuilder(words[bestPath.get(0)]);     for (int k = 1; k < n; ++k) {      final int i = bestPath.get(k - 1);      final int j = bestPath.get(k);      sb.append(words[j].substring(words[j].length() - cost[i][j]));    }     return sb.toString();  }   private int minLength;   // Returns the cost to append b after a.  private int getCost(final String a, final String b) {    int cost = b.length();    final int minLength = Math.min(a.length(), b.length());    for (int k = 1; k <= minLength; ++k)      if (a.substring(a.length() - k).equals(b.substring(0, k)))        cost = b.length() - k;    return cost;  }   // used: i-th bit means words[i] is used or not  private void dfs(String[] words, int[][] cost, List<Integer> path, List<Integer> bestPath,                   int used, int depth, int currLength) {    if (currLength >= minLength)      return;    if (depth == words.length) {      minLength = currLength;      bestPath.clear();      for (final int node : path) {        bestPath.add(node);      }      return;    }     for (int i = 0; i < words.length; ++i) {      if ((used >> i & 1) == 1)        continue;      path.add(i);      final int newLength =          depth == 0 ? words[i].length() : currLength + cost[path.get(depth - 1)][i];      dfs(words, cost, path, bestPath, used | 1 << i, depth + 1, newLength);      path.remove(path.size() - 1);    }  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗