A data structure supporting O(1) random access and worst-case O(1) append?

There is a beautiful structure called an extendible array that has worst-case O(1) insertion and O(n) memory overhead (that is, it’s asymptotically comparable to a dynamic array, but has O(1) worst-case insertion). The trick is to take the approach that the vector uses – doubling and copying – but to make the copying lazy. For … Read more

Smallest number that cannot be formed from sum of numbers from array

There’s a beautiful algorithm for solving this problem in time O(n + Sort), where Sort is the amount of time required to sort the input array. The idea behind the algorithm is to sort the array and then ask the following question: what is the smallest positive integer you cannot make using the first k … Read more

Represent directory tree as JSON

I don’t think that this task is a “wheel” (so to speak). But it is something which you can easily achieve by means of the tools you mentioned: import os import json def path_to_dict(path): d = {‘name’: os.path.basename(path)} if os.path.isdir(path): d[‘type’] = “directory” d[‘children’] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\ (path)] else: d[‘type’] = “file” … Read more

What’s the difference between set and map in C++?

They are semantically different. Consider: #include <set> #include <map> #include <utility> #include <iostream> using namespace std; int main() { pair<int, int> p1(1, 1); pair<int, int> p2(1, 2); set< pair<int, int> > s; s.insert(p1); s.insert(p2); map<int, int> m; m.insert(p1); m.insert(p2); cout << “Set size = ” << s.size() << endl; cout << “Map size = ” … Read more

How can natural numbers be represented to offer constant time addition?

As far as I know, Idris (a dependently-typed purely functional language which is very close to Haskell) deals with this in a quite straightforward way. Compiler is aware of Nats and Fins (upper-bounded Nats) and replaces them with machine integer types and operations whenever possible, so the resulting code is pretty effective. However, that’s not … Read more