Levenshtein distance algorithm's variant: calculate distance to make a string to be longest substring of other - algorithm

Are there any algorithm similar to Levenshtein distance algorithm, which can be described:
Original: the minimum number of single-character edits required to change one word into the other
What I want: the minimum number of single-character edits required to change one word to become the longest substring of the other
For eg:
s1 = "stak"
s2 = "stackoverflow"
1st modification: replace k character to c to make s1 to be stac, distance = 1, length = 4
2nd modification: add c between a and k to make s1 to be stack, distance = 1, length = 5
3rd modification: remove k to make s1 to be sta, distance = 1, length = 3
all 3 modifications have distance = 1 but the 2nd makes s1 to become longest substring with smallest distance to s2, so this is the modification what I want and stack is the string what I need
string Levenshtein(string s1, string s2);
my goal of this research to suggest the correct result set from user input which is entered a part of result string

Related

Stuck on how to make this palindrome pairs finding function be less than O(N^2)

Task here is to find palindromes formed by combining pairs of the original word list (so for below, stuff like "callac" and "laccal"). I thought I had an idea of pre-computing all the reversed versions of each word (N). Then for each original word, compare with each reversed word... but then we're back to N*N.
Maybe we could sort the list. And then for each word we're working on, do a binary search for words whose first character matches our word's first or last character and check from there resulting in some kind of N log N situation?
My code:
data = ["cal", "lac", "mic", "blah", "totally", "ylla", "rum", "mur", "listen", "netsil"]
def get_palindrome_pairs(words):
palindromes = []
for i in range(len(words)):
for j in range(i+1, len(words)):
combined = words[i] + words[j]
combined_swapped = words[j] + words[i]
if combined == combined[::-1]:
palindromes.append(combined)
if combined_swapped == combined_swapped[::-1]:
palindromes.append(combined_swapped)
return palindromes
print(get_palindrome_pairs(data))
Edit: my original algorithm did not work. The situation is, in fact, more complicated than this because you might have a ["abc", "ba"] situation where the combination gives you "abcba", which is a palindrome. You need to use a more sophisticated approach to account for this.
First, note that one can use a modified KMP algorithm to find, for any strings s1 and s2, all prefixes of (or, to be more precise, the lengths of all prefixes of) s1 which are suffixes of s2. This can be done in linear time. The basic version of KMP can be easily modified to find the longest prefix of s1 which is a suffix of s2; one can then use the backtracking table to find all the others.
Second, note that we can use this to find all palindromic prefixes of a string s in linear time. This is because a palindromic prefix of s is precisely a prefix of s which is a suffix of reversed(s).
Now suppose we have strings s and k, and length(s) >= length(k). Then ks is a palindrome iff we can write s = z reversed(k), where z is a palindrome.
To determine whether we have any s, k such that length(s) >= length(k) and ks is a palindrome, store all strings in a trie. Then, for each string s, find all its palindromic prefixes. Walk through s backwards to find all k in the trie such that reversed(k) is a suffix of s. If there is any such k, check to see if the corresponding prefix is a palindrome. If so, we have found k and s such that ks is a palindrome.
To determine whether we have any s, k such that length(s) >= length(k) and sk is a palindrome, it suffices to repeat the above step, but first reversing all the strings.
The total runtime will be O(k + n) where k is the total number of characters across all strings and n is the number of strings.

Find longest positive substrings in binary string

Let's assume I have a string like 100110001010001. I'd like to find such substring that:
are as longest as possible
have total positive sum >0
So the longest substrings, that have more 1s than 0s.
For example for the string above 100110001010001 it would be: [10011]000[101]000[1]
Actually it's be satisfying to find the total length of those, in this case: 9.
Unfortunately I have no clue, how can it be done not in brute-force way. Any ideas, please?
As posted now, your question seems a bit unclear. The total length of valid substrings that are "as long as possible" could mean different things: for example, among other options, it could be (1) a list of the longest valid extension to the left of each index (which would allow overlaps in the list), (2) the longest combination of non-overlapping such longest left-extensions, (3) the longest combination of non-overlapping, valid substrings (where each substring is not necessarily the longest possible).
I will outline a method for (3) since it easily transforms to (1) or (2). Finding the longest left-extension from each index with more ones than zeros can be done in O(n log n) time and O(n) additional space (for just the longest valid substring in O(n) time, see here: Finding the longest non-negative sub array). With that preprocessing, finding the longest combination of valid, non-overlapping substrings can be done with dynamic programming in somewhat optimized O(n^2) time and O(n) additional space.
We start by traversing the string, storing sums representing the partial sum up to and including s[i], counting zeros as -1. We insert each partial sum in a binary tree where each node also stores an array of indexes where the value occurs, and the leftmost index of a value less than the node's value. (A substring from s[a] to s[b] has more ones than zeros if the prefix sum up to b is greater than the prefix sum up to a.) If a value is already in the tree, we add the index to the node's index array.
Since we are traversing from left to right, only when a new lowest value is inserted into the tree is the leftmost-index-of-lower-value updated — and it's updated only for the node with the previous lowest value. This is because any nodes with a lower value would not need updating; and if any nodes with lower values were already in the tree, any nodes with higher values would already have stored the index of the earliest one inserted.
The longest valid substring to the left of each index extends to the leftmost index with a lower prefix sum, which can be easily looked up in the tree.
To get the longest combination, let f(i) represent the longest combination up to index i. Then f(i) equals the maximum of the length of each valid left extension possible to index j added to f(j-1).
Dynamic programming.
We have a string. If it is positive, that's our answer. Otherwise we need to trim each end until it goes positive, and find each pattern of trims. So for each length (N-1, N-2, N-3) etc, we've got N- length possible paths (trim from a, trim from b) each of which give us a state. When state goes positive, we've found out substring.
So two lists of integers, representing what happens if we trim entirely from a or entirely from b. Then backtrack. If we trim 1 from a, we must trim all the rest from b, if we trim two from a, we must trim one fewer from b. Is there an answer that allows us to go positive?
We can quickly eliminate because the answer must be at a maximum, either max trimming from a or max trimming from b. If the other trim allows us go positive, that's the result.
pseudocode:
N = length(string);
Nones = countones(string);
Nzeros = N - Nones;
if(Nones > Nzeroes)
return string
vector<int> cuta;
vector<int> cutb;
int besta = Nones - Nzeros;
int bestb = Nones - Nzeros;
cuta.push_back(besta);
cutb.push_back(bestb);
bestia = 0;
bestib = 0;
for(i=0;i<N;i++)
{
cuta.push_back( string[i] == 1 ? cuta.back() - 1 : cuta.back() +1);
cutb.push_back( string[N-i-1] == 1 ? cutb.back() -1 : cutb.back()+1);
if(cuta.back() > besta)
{
besta = cuta.back();
bestia = i;
}
if(cutb.back() > bestb)
{
bestb = cutb.back();
bestib = i;
}
// checks, is a cut from wholly from a or b going to send us positive
if(besta == 1)
answer = substring(string, bestia, N);
if(bestb == 1)
answer = substring(string, 0, N - bestib);
// if not, is a combined cut from current position to the
// the peak in the other distribution going to send us positive?
if(Nones - Nzeros + besta + cutb.back() == 1)
{
answer = substring(string, bestai, N - i);
}
if(Nones - Nzeros + cuta.back() + bestb == 1)
{
answer = substring(string, i, N - bestbi);
}
}
/*if we get here the string was all zeros and no positive substring */
This is untested and the final checks are a bit fiddly and I might have
made an error somewhere, but the algorithm should work more or less
as described.

How can I find such string in linear time using the suffix tree?

Given a string s of length n, find the longest string t that occurs both forwards and backwards in s.
e.g, s = yabcxqcbaz, then return t = abc or t = cba
I am considering using the generalized suffix tree but I think it would take me O(n^2) time.
i = 0 # Initialize the position on the S
j = 0 # Initialize the position on the Sr
n = len(S) # n is the length of the string
maxLengthPos = (0, 0) # Record the maximum length of such substring found so far and its position
# Iterate through every
for i in range(n):
for j in range(n):
maxL, pos = maxLengthPos
l = LCE(i, j) # The longest common extension which take O(1) time
if l > maxL:
maxLength = (l, i)
Can I implement it in O(n) time?
You are looking for the longest common substring of s and its reverse. This can indeed be solved using the generalized suffix array or suffix tree of s and reverse(s), in linear time.
There's a conceptionally simpler approach using the suffix automaton of s though. A suffix automaton is a finite automaton that matches exactly the suffixes of a string, and it can be built in linear time. You can find an implementation in C++ in my Github repository. Now you just feed the second string (in this case reverse(s)) into the automaton and record the longest match, which corresponds to the LCS of the two strings.

How to check if all substrings can be found in a dictionary

I have a problem that I want to solve as efficiently as possible. As an example,
I am given a string of words: A B C D and I have a 'dictionary' with 5 entries:
A
B C
B D
D
E
The dictionary tells me which substrings can be in my input string. And I want to check as efficiently as possible if the whole input string can be split into substrings so that all of them are found in the dictionary.
In the example the input string can be found by splitting it into A, B C and D
I'd like to know if there's a better way than just bruteforcing through all possible substrings. The less I check if a substring is in a dictionary the better.
It's not necessary to know which substrings couldn't be found in case there are no possible solutions.
Thank you.
I would use a tree instead of a dictionary. This will improve the search speed and will eliminate sub-trees for searching.
If you can use the same substring several time, there is a natural dynamic programming solution to this.
Let n be the size of your string. Let v be a vector of size n such that v[i] = true if and only if the substring made of the (n-i) last character of your original string can be broken down with your dictionary. Then you can fill the vector v backwards, starting at the last index decreasing i at each step.
In pseudo-code :
Let D be your dictionnary
Let s be your string
Let n be the size of s
(Let s[i:j] denote the substring of s made by characters between i and j (inclusive))
Let v be a vector of size n+1 filled with zeros
Let v[n] = 1
For int i = n-1; i>=0; i--
For int j = i; j <=n-1; j++
If (s[i:j] is in D) and (v[j+1] is equal to 1)
v[i] = 1
Exit the for loop
Return v[0]
You can make it run in O(N^2) by following method.
First store all your string in a trie.
Second, use dynamic programming approach to solve your problem. For each position i we will be calculating whether the substring of the first i symbols can be split into words from a dictionary (a trie). We will use, for simplicity, a forward-looking approach of dynamic programming.
So first we set that the substring of first 0 symbols can be split. Then we iterate from 0 to N-1. When we come to position i, we assume that we know the answer for this position already. If the split is possible, then we can go from this position and see which strings starting from this position are in the trie. For every such string, mark its end position as possible. By using the trie, we can do this in O(N) per one external loop iteration.
t = trie of given words
ans = {false}
ans[0] = true
for i=0..N-1
if ans[i] // if substring s[0]..s[i-1] can be split to given words
cur = t.root
for j=i to N-1 // go along all strings starting from position i
cur=cur.child(s[j]) // move to the child in trie
// therefore, the position cur corresponds to string
// s[i]...s[j]
if cur.isWordEnd // if there is a word in trie that ends in cur
ans[j+1] = true // the string s[0]..s[j] can be split
your answer is in ans[N]
Total time is O(N^2).

Optimal solution for non-overlapping maximum scoring sequences

While developing part of a simulator I came across the following problem. Consider a string of length N, and M substrings of this string with a non-negative score assigned to each of them. Of particular interest are the sets of substrings that meet the following requirements:
They do not overlap.
Their total score (by sum, for simplicity) is maximum.
They span the entire string.
I understand the naive brute-force solution is of O(M*N^2) complexity. While the implementation of this algorithm would probably not impose a lot on the performance of the whole project (nowhere near the critical path, can be precomputed, etc.), it really doesn't sit well with me.
I'd like to know if there are any better solutions to this problem and if so, which are they? Pointers to relevant code are always appreciated, but just algorithm description will do too.
This can be thought of as finding the longest path through a DAG. Each position in the string is a node and each substring match is an edge. You can trivially prove through induction that for any node on the optimal path the concatenation of the optimal path from the beginning to that node and from that node to the end is the same as the optimal path. Thanks to that you can just keep track of the optimal paths for each node and make sure you have visited all edges that end in a node before you start to consider paths containing it.
Then you just have the issue to find all edges that start from a node, or all substring that match at a given position. If you already know where the substring matches are, then it's as trivial as building a hash table. If you don't you can still build a hashtable if you use Rabin-Karp.
Note that with this you'll still visit all the edges in the DAG for O(e) complexity. Or in other words, you'll have to consider once each substring match that's possible in a sequence of connected substrings from start to the end. You could get better than this by doing preprocessing the substrings to find ways to rule out some matches. I have my doubts if any general case complexity improvements can come for this and any practical improvements depend heavily on your data distribution.
It is not clear whether M substrings are given as sequences of characters or indeces in the input string, but the problem doesn't change much because of that.
Let us have input string S of length N, and M input strings Tj. Let Lj be the length of Tj, and Pj - score given for string Sj. We say that string
This is called Dynamic Programming, or DP. You keep an array res of ints of length N, where the i-th element represents the score one can get if he has only the substring starting from the i-th element (for example, if input is "abcd", then res[2] will represent the best score you can get of "cd").
Then, you iterate through this array from end to the beginning, and check whether you can start string Sj from the i-th character. If you can, then result of (res[i + Lj] + Pj) is clearly achievable. Iterating over all Sj, res[i] = max(res[i + Lj] + Pj) for all Sj which can be applied to the i-th character.
res[0] will be your final asnwer.
inputs:
N, the number of chars in a string
e[0..N-1]: (b,c) an element of set e[a] means [a,b) is a substring with score c.
(If all substrings are possible, then you could just have c(a,b).)
By e.g. [1,2) we mean the substring covering the 2nd letter of the string (half open interval).
(empty substrings are not allowed; if they were, then you could handle them properly only if you allow them to be "taken" at most k times)
Outputs:
s[i] is the score of the best substring covering of [0,i)
a[i]: [a[i],i) is the last substring used to cover [0,i); else NULL
Algorithm - O(N^2) if the intervals e are not sparse; O(N+E) where e is the total number of allowed intervals. This is effectively finding the best path through an acyclic graph:
for i = 0 to N:
a[i] <- NULL
s[i] <- 0
a[0] <- 0
for i = 0 to N-1
if a[i] != NULL
for (b,c) in e[i]:
sib <- s[i]+c
if sib>s[b]:
a[b] <- i
s[b] <- sib
To yield the best covering triples (a,b,c) where cost of [a,b) is c:
i <- N
if (a[i]==NULL):
error "no covering"
while (a[i]!=0):
from <- a[i]
yield (from,i,s[i]-s[from]
i <- from
Of course, you could store the pair (sib,c) in s[b] and save the subtraction.
O(N+M) solution:
Set f[1..N]=-1
Set f[0]=0
for a = 0 to N-1
if f[a] >= 0
For each substring beginning at a
Let b be the last index of the substring, and c its score
If f[a]+c > f[b+1]
Set f[b+1] = f[a]+c
Set g[b+1] = [substring number]
Now f[N] contains the answer, or -1 if no set of substrings spans the string.
To get the substrings:
b = N
while b > 0
Get substring number from g[N]
Output substring number
b = b - (length of substring)

Resources