There are many ways to interpret a question. Are we looking for the intersection of sets represented by lists, or are we looking for the longest common subsequence? Are the lists always sorted?
In my recursive solution, I assume that we are looking for some longest subsequence , and I do not assume anything about the order of the elements:
private static <T> List<T> longestCommonSubseq(List<T> a, int indA, List<T> b, int indB){ if (indA == a.size() || indB == b.size()) return Collections.emptyList(); T itemA = a.get(indA); T itemB = b.get(indB); List<T> res; if (itemA.equals(itemB)){ res = new ArrayList<T>(); res.add(itemA); res.addAll(longestCommonSubseq(a, indA+1, b, indB+1)); }else{ List<T> opt1 = longestCommonSubseq(a, indA+1, b, indB); List<T> opt2 = longestCommonSubseq(a, indA, b, indB+1); if (opt1.size()>opt2.size()) res = opt1; else res = opt2; } return res; } public static <T> List<T> longestCommonSubseq(List<T> a, List<T> b){ return longestCommonSubseq(a,0,b,0); }
Note. For simplicity, in my decisions, lists should be random access (e.g. ArrayList).
source share