Computational complexity of base conversion

Naive base-conversion as you described takes quadratic time; you do about n bigint-by-smallint divisions, most of which take time linear in the size of the n-bit bigint. You can do base conversion in O(M(n) log(n)) time, however, by picking a power of target-base that’s roughly the square root of the to-be-converted number, doing divide-and-remainder by … Read more

How to print all possible balanced parentheses for an expression?

Here is actual code in Python, using generators to avoid using too much memory. #! /usr/bin/python def parenthesized (exprs): if len(exprs) == 1: yield exprs[0] else: first_exprs = [] last_exprs = list(exprs) while 1 < len(last_exprs): first_exprs.append(last_exprs.pop(0)) for x in parenthesized(first_exprs): if 1 < len(first_exprs): x = ‘(%s)’ % x for y in parenthesized(last_exprs): if … Read more

Binary tree level order traversal

Level order traversal is actually a BFS, which is not recursive by nature. It uses Queue instead of Stack to hold the next vertices that should be opened. The reason for it is in this traversal, you want to open the nodes in a FIFO order, instead of a LIFO order, obtained by recursion as … Read more