Find the number of occurrences of a subsequence in a string

This is a classical dynamic programming problem (and not typically solved using regular expressions). My naive implementation (count the 3’s for each 2 after each 1) has been running for an hour and it’s not done. That would be an exhaustive search approach which runs in exponential time. (I’m surprised it runs for hours though). … Read more

What’s the difference between recursion, memoization & dynamic programming? [duplicate]

Consider calculating the fibonacci sequence: Pure recursion: int fib(int x) { if (x < 2) return 1; return fib(x-1) + fib(x-2); } results in exponential number of calls. Recursion with memoization/DP: int fib(int x) { static vector<int> cache(N, -1); int& result = cache[x]; if (result == -1) { if (x < 2) result = 1; … Read more

What is the minimum cost to connect all the islands?

To approach this problem, I would use an integer programming framework and define three sets of decision variables: x_ij: A binary indicator variable for whether we build a bridge at water location (i, j). y_ijbcn: A binary indicator for whether water location (i, j) is the n^th location linking island b to island c. l_bc: … Read more

Find common substring between two strings

For completeness, difflib in the standard-library provides loads of sequence-comparison utilities. For instance find_longest_match which finds the longest common substring when used on strings. Example use: from difflib import SequenceMatcher string1 = “apple pie available” string2 = “come have some apple pies” match = SequenceMatcher(None, string1, string2).find_longest_match() print(match) # -> Match(a=0, b=15, size=9) print(string1[match.a:match.a + … Read more

Why is the knapsack problem pseudo-polynomial?

The running time is O(NW) for an unbounded knapsack problem with N items and knapsack of size W. W is not polynomial in the length of the input though, which is what makes it pseudo-polynomial. Consider W = 1,000,000,000,000. It only takes 40 bits to represent this number, so input size = 40, but the … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)