Find cycle of shortest length in a directed graph with positive weights

You can easily modify Floyd-Warshall algorithm. (If you’re not familiar with graph theory at all, I suggest checking it out, e.g. getting a copy of Introduction to Algorithms). Traditionally, you start path[i][i] = 0 for each i. But you can instead start from path[i][i] = INFINITY. It won’t affect algorithm itself, as those zeroes weren’t … Read more

Iterating over a Binary Tree with O(1) Auxiliary Space

Geez, I’ll have to actually type it up from Knuth. This solution is by Joseph M. Morris [Inf. Proc. Letters 9 (1979), 197-200]. As far as I can tell, it runs in O(NlogN) time. static void VisitInO1Memory (Node root, Action<Node> preorderVisitor) { Node parent = root ; Node right = null ; Node curr ; while (parent != null) { curr … Read more

How Can I Best Guess the Encoding when the BOM (Byte Order Mark) is Missing?

Maybe you can shell out to a Python script that uses Chardet: Universal Encoding Detector. It is a reimplementation of the character encoding detection that used by Firefox, and is used by many different applications. Useful links: Mozilla’s code, research paper it was based on (ironically, my Firefox fails to correctly detect the encoding of … Read more

Fuzzy date algorithm

There is a property in NSDateFormatter – “doesRelativeDateFormatting”. It appears only in 10.6/iOS4.0 and later but it will format a date into a relative date in the correct locale. From Apple’s Documentation: If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” … Read more

Fastest available algorithm for distance transform

This paper reviews the known exact distance transform algorithms: “2D Euclidean distance transform algorithms: A comparative survey” The fastest exact distance transform is from Meijster: “A General Algorithm for Computing Distance Transforms in Linear Time.” The design of the algorithm is particularly well suited for parallel calculation. This is implemented in my open … Read more

What is the algorithm that opencv uses for finding contours?

If you read the documentation it is mentioned this function implements the algorithm of: Suzuki, S. and Abe, K., Topological Structural Analysis of Digitized Binary Images by Border Following. CVGIP 30 1, pp 32-46 (1985) OpenCV is open source if you want to see how this is implemented just need to read the code: … Read more

O(klogk) time algorithm to find kth smallest element from a binary heap

Well, your intuition was right that we need extra data structure to achieve O(klogk) because if we simply perform operations on the original heap, the term logn will remain in the resulting complexity. Guessing from the targeted complexity O(klogk), I feel like creating and maintaining a heap of size k to help me achieve the … Read more