Longest Common Prefix with C# and LINQ

Friday, May 10, 2013

I recently can across an interesting problem:  Given a set of n directories, find the most nested directory that is an ancestor of all of them.  This is equivalent to finding the longest common prefix. For example, if I have the following paths: /dir1/dir2/dir3 /dir1/dir2/dir4 Then the longest common prefix is just /dir1/dir2.  If we now add /dir1/dir5 to the set, we get: /dir1/dir2/dir3 /dir1/dir2/dir4 /dir1/dir5 Then the longest common prefix changes to /dir1.  In order to do this, I start by comparing the first and second directories by splitting them on the / symbol, and then comparing the elements of the resulting arrays. ...
one comment