Is the time-complexity of iterative string append actually O(n^2), or O(n)?

In CPython, the standard implementation of Python, there’s an implementation detail that makes this usually O(n), implemented in the code the bytecode evaluation loop calls for + or += with two string operands. If Python detects that the left argument has no other references, it calls realloc to attempt to avoid a copy by resizing … Read more

nth fibonacci number in sublinear time

Following from Pillsy’s reference to matrix exponentiation, such that for the matrix M = [1 1] [1 0] then fib(n) = Mn1,2 Raising matrices to powers using repeated multiplication is not very efficient. Two approaches to matrix exponentiation are divide and conquer which yields Mn in O(ln n) steps, or eigenvalue decomposition which is constant … Read more

Javascript ES6 computational/time complexity of collections

Right from that very paragraph your linked to: Set objects must be implemented using [mechanisms] that, on average, provide access times that are sublinear on the number of elements in the collection. You will find the same sentence for Maps, WeakMaps and WeakSets. It looks the ECMA spec mandates that the implementations (e.g. Set.prototype.has) are … 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