views:

50052

answers:

60

There a some data structures around that are really cool but are unknown to most programmers. Which are they?

Everybody knows linked lists, binary trees, and hashes, but what about Skip lists, Bloom filters for example. I would like to know more data structures that are not so common, but are worth knowing because they rely on great ideas and enrich a programmer's tool box.

PS: I am also interested on techniques like Dancing links which make interesting use of the properties of a common data structure.

EDIT: Please try to include links to pages describing the data structures in more detail. Also, try to add a couple of words on why a data structures is cool (as Jonas Kölker already pointed out). Also, try to provide one data-structure per answer. This will allow the better data structures to float to the top based on their votes alone.

+100  A: 

Tries, also known as prefix-trees or crit-bit trees, have existed for over 40 years but are still relatively unknown. A very cool use of tries is described in "TRASH - A dynamic LC-trie and hash data structure", which combines a trie with a hash function.

David Phillips
Tries are a good one for sure, only remember what they are as its was on my Data Structures and Algorithms exam.
Mark Davidson
very commonly used by spell-checkers
Steven A. Lowe
Burst tries are also an interesting variant, where you use only a prefix of the strings as nodes and otherwise store lists of strings in the nodes.
Torsten Marek
The regex engine in Perl 5.10 automatically creates tries.
Brad Gilbert
In my experience tries are painfully expensive, given that a pointer is generally longer than a char, which is a shame. They're only suitable for certain data-sets.
Joe
We make use of tries in the project I work on. We use them for partitioning 2D space and then quickly determining which partition contains a given point.
Scottie T
@Joe: Those are problems with naive trie implementations. In practice, you usually have a much higher branching factor that a single char and you usually compress lines in the tree in order to store common sequences of chars (like syllables) in a single node.
Jon Harrop
Tries are used in the T9 cell-phone auto-complete, yes?
Paul Nathan
+9  A: 

How about splay trees?

Also, Chris Okasaki's purely functional data structures come to mind.

starblue
+31  A: 

Here are a few:

  • Suffix tries. Useful for almost all kinds of string searching (http://en.wikipedia.org/wiki/Suffix_trie#Functionality). See also suffix arrays; they're not quite as fast as suffix trees, but a whole lot smaller.

  • Splay trees (as mentioned above). The reason they are cool is threefold:

    • They are small: you only need the left and right pointers like you do in any binary tree (no node-color or size information needs to be stored)
    • They are (comparatively) very easy to implement
    • They offer optimal amortized complexity for a whole host of "measurement criteria" (log n lookup time being the one everybody knows). See http://en.wikipedia.org/wiki/Splay_tree#Performance_theorems
  • Heap-ordered search trees: you store a bunch of (key, prio) pairs in a tree, such that it's a search tree with respect to the keys, and heap-ordered with respect to the priorities. One can show that such a tree has a unique shape (and it's not always fully packed up-and-to-the-left). With random priorities, it gives you expected O(log n) search time, IIRC.

  • A niche one is adjacency lists for undirected planar graphs with O(1) neighbour queries. This is not so much a data structure as a particular way to organize an existing data structure. Here's how you do it: every planar graph has a node with degree at most 6. Pick such a node, put its neighbors in its neighbor list, remove it from the graph, and recurse until the graph is empty. When given a pair (u, v), look for u in v's neighbor list and for v in u's neighbor list. Both have size at most 6, so this is O(1).

By the above algorithm, if u and v are neighbors, you won't have both u in v's list and v in u's list. If you need this, just add each node's missing neighbors to that node's neighbor list, but store how much of the neighbor list you need to look through for fast lookup.

Jonas Kölker
You couldn't just list one per answer, could ya? Makes it easier for the single, good data structures to float to the top.
KingNestor
I could, but I'm still not /quite/ getting the hang of this weird wiki/forum hybrid. I'm not gonna edit right now (eat-sleep-rinse-repeat), and I'm probably gonna forget to do it later ;)
Jonas Kölker
The Heap ordered search tree is called a treap. One trick you can do with these is change the priority of a node to push it to the bottom of the tree where its easier to delete.
paperhorse
"The Heap ordered search tree is called a treap." -- In the definition I've heard, IIRC, a treap is a heap-ordered search tree with *random* priorities. You could choose other priorities, depending on the application...
Jonas Kölker
A suffix *trie* is almost but not quite the same as the much cooler suffix *tree*, which has strings and not individual letters on its edges and can be built in linear time(!). Also despite being asymptotically slower, in practice suffix arrays are often much faster than suffix trees for many tasks because of their smaller size and fewer pointer indirections. Love the O(1) planar graph lookup BTW!
j_random_hacker
@j_random_hacker: suffix arrays are not asymptotically slower. Here is ~50 lines of code for linear suffix array construction: http://www.cs.helsinki.fi/u/tpkarkka/publications/icalp03.pdf
Edward Kmett
@Edward Kmett: I have in fact read that paper, it was quite a breakthrough in suffix array *construction*. (Although it was already known that linear time construction was possible by going "via" a suffix tree, this was the 1st undeniably practical "direct" algorithm.) But some operations outside of construction are still asymptotically slower on a suffix array unless a LCA table is also built. That can also be done in O(n), but you lose the size and locality benefits of the pure suffix array by doing so.
j_random_hacker
@j_random_hacker: Fair enough. Out of context it wasn't clear to me which asymptotics you were referring to.
Edward Kmett
+38  A: 

Spatial Indices, in particular R-trees and KD-trees, store spatial data efficiently. They are good for geographical map coordinate data and VLSI place and route algorithms, and sometimes for nearest-neighbor search.

Bit Arrays store individual bits compactly and allow fast bit operations.

Yuval F
Spatial indices are also useful for N-body simulations involving long-range forces like gravity.
Justin Peel
+7  A: 

Van Emde-Boas trees. I have even a C++ implementation of it, for up to 2^20 integers.

zvrba
+19  A: 

<zvrba> Van Emde-Boas trees

I think it'd be useful to know why they're cool. In general, the question "why" is the most important to ask ;)

My answer is that they give you O(log log n) dictionaries with {1..n} keys, independent of how many of the keys are in use. Just like repeated halving gives you O(log n), repeated sqrting gives you O(log log n), which is what happens in the vEB tree.

Jonas Kölker
I fully agree that "why" is important, but that was not included in the question ;)
zvrba
They are nice from a theoretical point of view. In practice, however, it's quite tough to get competetive performance out of them. The paper I know got them to work well up to 32 bit keys (http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.2.7403) but the approach will not scale to more than maybe 34-35 bits or so and there is no implementation of that.
Manuel
Another reason why they are cool is that they are a key building block for a number of cache-oblivious algorithms.
Edward Kmett
+11  A: 
  • Kd-Trees, spatial data structure used (amongst others) in Real-Time Raytracing, has the downside that triangles that cross intersect the different spaces need to be clipped. Generally BVH's are faster because they are more lightweight.
  • MX-CIF Quadtrees, store bounding boxes instead of arbitrary point sets by combining a regular quadtree with a binary tree on the edges of the quads.
  • HAMT, hierarchical hash map with access times that generally exceed O(1) hash-maps due to the constants involved.
  • Inverted Index, quite well known in the search-engine circles, because it's used for fast retrieval of documents associated with different search-terms.

Most, if not all, of these are documented on the NIST Dictionary of Algorithms and Data Structures

Jasper Bekkers
Added links to the datastructures for you.
Simucal
+5  A: 

Pairing heaps are a type of heap data structure with relatively simple implementation and excellent practical amortized performance.

Marko Tintor
The source code of the book "Data Structures and Algorithm Analysis in Java/C++" seems to include implementations of Pairing-Heapshttp://users.cs.fiu.edu/~weiss/dsaa_c++3/code/http://users.cs.fiu.edu/~weiss/dsaajava2/code/
f3lix
+83  A: 

Bloom filter: Bit array of m bits, initially all set to 0.

To add an item you run it through k hash functions that will give you k indices in the array which you then set to 1.

To check if an item is in the set, compute the k indices and check if they are all set to 1.

Of course, this gives some probability of false-positives (according to wikipedia it's about 0.61^(m/n) where n is the number of inserted items). False-negatives are not possible.

Removing an item is impossible, but you can implement counting bloom filter, represented by array of ints and increment/decrement.

lacop
You forget to mention their use with dictionaries :) You can squeeze a full dictionary into a bloom filter with about 512k, like a hashtable without the values
Chris S
Google cites the use of Bloom filters in there implementation of BigTable.
Brian Gianforcaro
So this is useful because it allows us to cheaply test for the existence of an element in a set? (I'm new to bloom filters.)
FreshCode
@FreshCode It actually lets you cheaply test for the *absence* of an element in the set since you can get false positives but never false negatives
Tom Savage
@FreshCode As @Tom Savage said, it's more useful when checking for negatives. For example, you can use it as a fast and small (in terms of memory usage) spell checker. Add all of the words to it and then try to look up words the user enters. If you get a negative it means it's misspelled. Then you can run some more expensive check to find closest matches and offer corrections.
lacop
Google Chrome implements the Safe Browsing filter using a bloom filter. Isn't this case more appropriate for checking for positives?
abhin4v
@abhin4v: Bloom filters are often used when most requests are likely to return an answer of "no" (such as the case here), meaning that the small number of "yes" answers can be checked with a slower exact test. This still results in a big reduction in the *average* query response time. Don't know if Chrome's Safe Browsing does that, but that would be my guess.
j_random_hacker
+2  A: 

Splay Trees are cool. They reorder themselves in a way that moves the most often queried elements closer to the root.

mdm
+5  A: 

I like treaps - for the simple, yet effective idea of superimposing a heap structure with random priority over a binary search tree in order to balance it.

Rafał Dowgird
+6  A: 
  • Binary decision diagram (my very favorite data structure, good for representing boolean equations, and solving them. Effective for a great lot of things)
  • Heaps (a tree where the parent of a node always maintains some relation to the children of the node, for instance, the parent of a node is always greater than each of it's children (max-heap) )
  • Priority Queues (really just min-heaps and max-heaps, good for maintaining order of a lot of elements there the e.g. the item with the highest value is supposed to be removed first)
  • Hash tables, (with all kinds of lookup strategies, and bucket overflow handling)
  • Balanced binary search trees (Each of these have their own advantages)
    • RB-trees (overall good, when inserting, lookup, removing and iterating in an ordered fashion)
    • Avl-trees (faster for lookup than RB, but otherwise very similar to RB)
    • Splay-trees (faster for lookup when recently used nodes are likely to be reused)
    • Fusion-tree (Exploiting fast multiplication for getting even better lookup times)
    • B+Trees (Used for indexing in databases and file systems, very efficient when latency to read/write from/to the index is significant).
  • Spatial indexes ( Excellent for querying for whether points/circles/rectangles/lines/cubes is in close proximity to or contained within each other)
    • BSP tree
    • Quadtree
    • Octree
    • Range-tree
    • Lots of similar but slightly different trees, and different dimensions
  • Interval trees (good finding overlapping intervals, linear)
  • Graphs
    • adjacency list (basically a list of edges)
    • adjacency matrix (a table representing directed edges of a graph with a single bit per edge. Very fast for graph traversal)

These are the ones i can come to think of. There are even more on wikipedia about data structures

Zuu
Thanks for giving constructive critique before downvoting this answer </sarcasm>
Zuu
Not the downvoter, but I'd guess it's because Heaps, PQs, Hash Tables and Binary Trees aren't what you'd call lesser known.
Dana
@Zuu, Ok, I'll give some constructive criticism. You provided many data structures, of which only a small fraction could be considered "lesser known". There are no links in your post and it generally misses the entire point of the question.
Simucal
It's hard to tell what people would understand by 'lesser known'. Some people barely know what a balanced tree is. And while people might know the term 'heap' they don't know it's a general data structure that can actually be used with sense in a given application.
Zuu
What goes for the links, sure i could look it all up, but i was nice enough to categorize them as well as linking to an index of data structures on Wikipedia. Also note that the last part of the question was added after i posted this answer :-)
Zuu
BDDs. Fear the most mindwarping datastructure :)
Tetha
What do you mean by saying Interval trees are "linear"?
wrang-wrang
+55  A: 

Skip lists are pretty neat.

Wikipedia
A skip list is a probabilistic data structure, based on multiple parallel, sorted linked lists, with efficiency comparable to a binary search tree (order log n average time for most operations).

They can be used as an alternative to balanced trees (using probalistic balancing rather than strict enforcement of balancing). They are easy to implement and faster than say, a red-black tree. I think they should be in every good programmers toolchest.

If you want to get an in-depth introduction to skip-lists here is a link to a video of MIT's Introduction to Algorithms lecture on them.

Also, here is a Java applet demonstrating Skip Lists visually.

Simucal
+59  A: 

Rope: It's a string that allows for cheap prepends, substrings, middle insertions and appends. I've really only had use for it once, but no other structure would have sufficed. Regular strings and arrays prepends were just far too expensive for what we needed to do, and reversing everthing was out of the question.

Patrick
I've had thoughts of something like this for my own uses. Nice to know it's already been implemented somewhere else.
Kibbee
There's an implementation in the SGI STL (1998): http://www.sgi.com/tech/stl/Rope.html
quark
Without knowing what is was called I recently wrote something very similar to this for Java - performance has been excellent:http://code.google.com/p/mikeralib/source/browse/trunk/Mikera/src/mikera/persistent/Text.java
mikera
Rope is pretty rare: http://stackoverflow.com/questions/1863440/is-there-any-scenario-where-the-rope-data-structure-is-more-efficient-than-a-stri
Will
There was a nice article about ropes on Good Math, Bad Math: http://scienceblogs.com/goodmath/2009/01/ropes_twining_together_strings.php
Kuroki Kaze
+22  A: 

I think Disjoint Set is pretty nifty for cases when you need to divide a bunch of items into distinct sets and query membership. Good implementation of the Union and Find operations result in amortized costs that are effectively constant (inverse of Ackermnan's Function, if I recall my data structures class correctly).

Dana
This is also called the *"union-find data structure."* I was in awe when I first learned about this clever data structure in algorithms class...
BlueRaja - Danny Pflughoeft
I wouldn't really call it 'lesser known', but +1 for mentioning it.
MAK
+22  A: 

Anyone with experience in 3D rendering should be familiar with BSP trees. Generally, it's the method by structuring a 3D scene to be manageable for rendering knowing the camera coordinates and bearing.

Binary space partitioning (BSP) is a method for recursively subdividing a space into convex sets by hyperplanes. This subdivision gives rise to a representation of the scene by means of a tree data structure known as a BSP tree.

In other words, it is a method of breaking up intricately shaped polygons into convex sets, or smaller polygons consisting entirely of non-reflex angles (angles smaller than 180°). For a more general description of space partitioning, see space partitioning.

Originally, this approach was proposed in 3D computer graphics to increase the rendering efficiency. Some other applications include performing geometrical operations with shapes (constructive solid geometry) in CAD, collision detection in robotics and 3D computer games, and other computer applications that involve handling of complex spatial scenes.

spoulson
John Carmac FTW
BlueRaja - Danny Pflughoeft
+5  A: 

Enhanced hashing algorithms are quite interesting. Linear hashing is neat, because it allows splitting one "bucket" in your hash table at a time, rather than rehashing the entire table. This is especially useful for distributed caches. However, with most simple splitting policies, you end up splitting all buckets in quick succession, and the load factor of the table oscillates pretty badly.

I think that spiral hashing is really neat too. Like linear hashing, one bucket at a time is split, and a little less than half of the records in the bucket are put into the same new bucket. It's very clean and fast. However, it can be inefficient if each "bucket" is hosted by a machine with similar specs. To utilize the hardware fully, you want a mix of less- and more-powerful machines.

erickson
I had to use linear hashing in a database class! Cool stuff.
trinithis
+3  A: 

Binary decision diagram is one of my favorite data structures, or in fact Reduced Ordered Binary Decision Diagram (ROBDD).

These kind of structures can for instance be used for:

  • Representing sets of items and performing very fast logical operations on those sets.
  • Any boolean expression, with the intention of finding all solutions for the expression

Note that many problems can be represented as a boolean expression. For instance the solution to a suduku can be expressed as a boolean expression. And building a BDD for that boolean expression will immediately yield the solution(s).

Zuu
I thought sudoku was NP-hard?
SDX2000
+14  A: 

Huffman trees - used for compression.

Lurker Indeed
+17  A: 

Circular or ring buffer - used for streaming, among other things.

cdonner
This is most common data structure for buffering data. I think that this one is first one introduced in our class.
ralu
+3  A: 

Counted unsorted balanced btrees.

Perfect for text editor buffers.

http://www.chiark.greenend.org.uk/~sgtatham/algorithms/cbtree.html

Blank Xavier
+3  A: 

I like suffix tree and arrays for string processing, skip lists for balanced lists and splay trees for automatic balancing trees

+1  A: 

Take a look at the sideways heap, presented by Donald Knuth.

http://stanford-online.stanford.edu/seminars/knuth/071203-knuth-300.asx

Yngve Sneen Lindal
+8  A: 

An interesting variant of the hash table is called Cuckoo Hashing. It uses multiple hash functions instead of just 1 in order to deal with hash collisions. Collisions are resolved by removing the old object from the location specified by the primary hash, and moving it to a location specified by an alternate hash function. Cuckoo Hashing allows for more efficient use of memory space because you can increase your load factor up to 91% with only 3 hash functions and still have good access time.

A. Levy
Check hopscotch hashing claimed to be faster.
chmike
A: 

Getting away from all these graph structures, I just love the simple Ring-Buffer.

When properly implemented you can seriously reduce you memory footprint while maintaining performance and sometimes even improving it.

Explaining the properties of a Ring-Buffer or adding a link to more information would be helpful to people who don't know what it is...which is kind of the point of this question!
A. Levy
Duplicates an existing answer above.
Steve Guidi
+2  A: 

Fast Compact tries:

bill
http://nothings.org/computer/judy/
Jon Harrop
+1  A: 

Binomial heap's have a lot of interesting properties, most useful of which is merging.

DShook
+13  A: 

Fibonacci heaps

They're used in some of the fastest known algorithms (asymptotically) for a lot of graph-related problems, such as the Shortest Path problem. Dijkstra's algorithm runs in O(E log V) time with standard binary heaps; using Fibonacci heaps improves that to O(E + V log V), which is a huge speedup for sparse graphs. Unfortunately, though, they have a high constant factor, often making them impractical in practice.

Adam Rosenfield
High constant factor as you said, and hard to implement well according to a friend who had to. Fianally not that cool, but still, maybe worth knowing.
p4bl0
These guys here made them run competetive in comparison to other heap kinds: http://www.cphstl.dk/Presentation/SEA2010/SEA-10.pdfThere is a related data structure called Pairing Heaps that's easier to implement and that offers pretty good practical performance. However, the theoretical analysis is partially open.
Manuel
+17  A: 

I think lock-free alternatives to standard data structures i.e lock-free queue, stack and list are much overlooked.
They are increasingly relevant as concurrency becomes a higher priority and are much more admirable goal than using Mutexes or locks to handle concurrent read/writes.

Here's some links
http://www.cl.cam.ac.uk/research/srg/netos/lock-free/
http://www.research.ibm.com/people/m/michael/podc-1996.pdf [Links to PDF]
http://www.boyet.com/Articles/LockfreeStack.html

Mike Acton's (often provocative) blog has some excellent articles on lock-free design and approaches

zebrabox
+3  A: 

You can use a min-heap to find the minimum element in constant time, or a max-heap to find the the maximum element. But what if you wanted to do both operations? You can use a Min-Max to do both operations in constant time. It works by using min max ordering: alternating between min and max heap comparison between consecutive tree levels.

Firas Assaad
This is one of my favourite data structures. There is even a variant called a min-max-median heap which allows O(1) retrieval of any of the three.
Martin
How are these related to finger trees?
Jon Harrop
+8  A: 

I'm surprised no one has mentioned Merkle trees (ie. Hash Trees).

Used in many cases (P2P programs, digital signatures) where you want to verify the hash of a whole file when you only have part of the file available to you.

BlueRaja - Danny Pflughoeft
+2  A: 

One lesser known, but pretty nifty data structure is the Fenwick Tree (also sometimes called a Binary Indexed Tree or BIT). It stores cumulative sums and supports O(log(n)) operations. Although cumulative sums might not sound very exciting, it can be adapted to solve many problems requiring a sorted/log(n) data structure.

IMO, its main selling point is the ease with which can be implemented. Very useful in solving algorithmic problems that would involve coding a red-black/avl tree otherwise.

MAK
+1, can't believe so few people know of this structure. Its extremely easy to implement, its pretty much a magical Unicorn that can solve any problem.
Martín Fixman
+11  A: 

Have a look at Finger Trees, especially if you're a fan of the previously mentioned purely functional data structures. They're a functional representation of persistent sequences supporting access to the ends in amortized constant time, and concatenation and splitting in time logarithmic in the size of the smaller piece.

As per the original article:

Our functional 2-3 finger trees are an instance of a general design technique in- troduced by Okasaki (1998), called implicit recursive slowdown. We have already noted that these trees are an extension of his implicit deque structure, replacing pairs with 2-3 nodes to provide the flexibility required for efficient concatenation and splitting.

A Finger Tree can be parameterized with a monoid, and using different monoids will result in different behaviors for the tree. This lets Finger Trees simulate other data structures.

You may also want to glance at markcc's blog post on finger trees.

huitseeker
A: 

A proper string data structure. Almost every programmer settles for whatever native support that a language has for the structure and that's usually inefficient (especially for building strings, you need a separate class or something else).

The worst is treating a string as a character array in C and relying on the NULL byte for safety.

omouse
The other extreme is C++, where every self-respecting library comes with its own string data type, which is of course incompatible with all the other string types except `const char*`. Personally, I prefer the environments where I don't have to spend so much time converting strings from one type to another.
nikie
+21  A: 

Zippers - derivatives of data structures that modify the structure to have a natural notion of 'cursor' -- current location. These are really useful as they guarantee indicies cannot be out of bound -- used, e.g. in the xmonad window manager to track which window has focused.

Amazingly, you can derive them by applying techniques from calculus to the type of the original data structure!

Don Stewart
this is only useful in functional programming (in imperative languages you just keep a pointer or an index). Also tbh I still don't get how Zippers really work.
Stefan Monov
@Stefan the point is that you don't need to keep a separate index or pointer now.
Don Stewart
+7  A: 

Nested sets are nice for representing trees in the relational databases and running queries on them. For instance, ActiveRecord (Ruby on Rails' default ORM) comes with a very simple nested set plugin, which makes working with trees trivial.

esad
+1 Yep, nested sets rule ;-)
alexander.biskop
+1  A: 

PQ-Trees

+2  A: 

I personally find sparse matrix data structures to be very interesting. http://www.netlib.org/linalg/html_templates/node90.html

The famous BLAS libraries use these. And when you deal with linear systems that contain 100,000's of rows and columns, it becomes critical to use these. Some of these also resemble the compact grid (basically like a bucket-sorted grid) which is common in computer graphics. http://www.cs.kuleuven.be/~ares/publications/LD08CFRGRT/LD08CFRGRT.pdf

Also as far as computer graphics is concerned, MAC grids are somewhat interesting, but only because they're clever. http://www.seas.upenn.edu/~cis665/projects/Liquation_665_Report.pdf

CJJ
A: 

Zipper is yet another simple data structure which is very useful in looking at a specific node of a tree or a list (like for example text editing, xml trees etc) in a functional programming perspective.

Ramakrishnan Muthukrishnan
dupe, someone already posted zippers
Neil N
+2  A: 

It's pretty domain-specific, but half-edge data structure is pretty neat. It provides a way to iterate over polygon meshes (faces and edges) which is very useful in computer graphics and computational geometry.

Mark
+1  A: 

Priority deque is cheaper than having to maintain 2 separate priority queues with different orderings. http://www.alexandria.ucsb.edu/middleware/javadoc/edu/ucsb/adl/middleware/PriorityDeque.html http://cphstl.dk/Report/Priority-deque/cphstl-report-2001-14.pdf

ade
+1  A: 

Delta list/delta queue are used in programs like cron or event simulators to work out when the next event should fire. http://everything2.com/title/delta+list http://www.cs.iastate.edu/~cs554/lec_notes/delta_clock.pdf

ade
+6  A: 

Left Leaning Red-Black Trees. A significantly simplified implementation of red-black trees by Robert Sedgewick published in 2008 (~half the lines of code to implement). If you've ever had trouble wrapping your head around the implementation of a Red-Black tree, read about this variant.

Very similar (if not identical) to Andersson Trees.

Lucas
+3  A: 

Not really a data structure; more of a way to optimize dynamically allocated arrays, but the gap buffers used in Emacs are kind of cool.

kerkeslager
+5  A: 

Scapegoat trees. A classic problem with plain binary trees is that they become unbalanced (e.g. when keys are inserted in ascending order.)

Balanced binary trees (AKA AVL trees) waste a lot of time balancing after each insertion.

Red-Black trees stay balanced, but require a extra bit of storage for each node.

Scapegoat trees stay balanced like red-black trees, but don't require ANY additional storage. They do this by analyzing the tree after each insertion, and making minor adjustments. See http://en.wikipedia.org/wiki/Scapegoat_tree.

+3  A: 

BK-Trees, or Burkhard-Keller Trees are a tree-based data structure which can be used to quickly find near-matches to a string.

Ashish
A: 

Environment tracking recursive structures.

Compilers use a structure that is recursive but not like a tree. Inner scopes have a pointer to an enclosing scope so the nesting is inside-out. Verifying whether a variable is in scope is a recursive call from the inside scope to the enclosing scope.

public class Env
{    
    HashMap<String, Object> map;
    Env                     outer;

    Env()
    {
        outer = null;
        map = new HashMap();
    }

    Env(Env o)
    {
        outer = o;
        map = new HashMap();
    }

    void put(String key, Object value)
    {
        map.put(key, value);
    }

    Object get(String key)
    {
        if (map.containsKey(key))
        {
            return map.get(key);
        }
        if (outer != null)
        {
            return outer.get(key);
        }
        return null;
    }

    Env push()
    {
        return new Env(this);
    }

    Env pop()
    {
        return outer;
    }
}

I'm not sure if this structure even has a name. I call it an inside-out list.

Kelly French
+1  A: 

There is a clever Data-structure out there that uses Arrays to save the Data of the Elements, but the Arrays are linked together in an Linked-List/Array.

This does have the advantage that the iteration over the elements is very fast (faster than a pure linked-list approach) and the costs for moving the Arrays with the Elements around in Memory and/or (de-)allocation are at a minimum. (Because of this this data-structure is usefull for Simulation stuff).

I know about it from here:

http://software.intel.com/en-us/blogs/2010/03/26/linked-list-verses-array/

"...and that an additional array is allocated and linked in to the cell list of arrays of particles. This is similar in some respects to how TBB implemented its concurrent container."(it is about ther Performance of Linked Lists vs. Arrays)

Quonux
In C++'s standard library, this is known as a deque: http://www.cplusplus.com/reference/stl/deque/
Josh Townzen
This brings http://en.wikipedia.org/wiki/VList to my mind ...
f3lix
+3  A: 

Persistent Data Structures

Vaibhav Bajpai
+1  A: 

Someone else already proposed Burkhard-Keller-Trees, but I thought I might mention them again in order to plug my own implementation. :)

http://well-adjusted.de/mspace.py/index.html

There are faster implementations around (see ActiveState's Python recipes or implementations in other languages), but I think/hope my code helps to understand these data structures.

By the way, both BK and VP trees can be used for much more than searching for similar strings. You can do similarity searches for arbitrary objects as long as you have a distance function that satisfies a few conditions (positivity, symmetry, triangle inequality).

Jochen
+5  A: 

Splash Tables are great. They're like a normal hash table, except they guarantee constant-time lookup and can handle 90% utilization without losing performance. They're a generalization of the Cuckoo Hash (also a great data structure). They do appear to be patented, but as with most pure software patents I wouldn't worry too much.

David Seiler
A: 

Bucket Brigade

They are used extensively in Apache. Basically they are a linked list that loops around on itself in a ring. I am not sure if they are used outside of Apache and Apache modules but they fit the bill as a cool yet lesser known data structure. A bucket is a container for some arbitrary data and a bucket brigade is a collection of buckets. The idea is that you want to be able to modify and insert data at any point in the structure.

Lets say that you have a bucket brigade that contains an html document with one character per bucket. You want to convert all the < and > symbols into &lt; and &gt; entities. The bucket brigade allows you to insert some extra buckets in the brigade when you come across a < or > symbol in order to fit the extra characters required for the entity. Because the bucket brigade is in a ring you can insert backwards or forwards. This is much easier to do (in C) than using a simple buffer.

Some reference on bucket brigades below:

Apache Bucket Brigade Reference

Introduction to Buckets and Brigades

John Scipione
Sounds like a marketing name for a circular linked list
BlueRaja - Danny Pflughoeft
Yeah, it sounds like a circular linked list with a variant record type along with some O(1) insertion properties.
Paul Nathan
+1  A: 

I had good luck with WPL Trees before. A tree variant that minimizes the weighted path length of the branches. Weight is determined by node access, so that frequently-accessed nodes migrate closer to the root. Not sure how they compare to splay trees, as I've never used those.

TMN
+5  A: 

Ball Trees. Just because they make people giggle.

A ball tree is a data structure that indexes points in a metric space. Here's an article on building them. They are often used for finding nearest neighbors to a point or accelerating k-means.

Think you could give a link too?
j_random_hacker
There you go. They are a little obscure, I grant you.
Thanks! (pad, pad, pad)
j_random_hacker
These are also commonly known as "vantage point" trees or vp-trees.http://en.wikipedia.org/wiki/Vp-tree
Edward Kmett
+5  A: 

Fenwick Tree. It's a data structure to keep count of the sum of all elements in a vector, between two given subindexes i and j. The trivial solution, precalculating the sum since the begining doesn't allow to update a item (you have to do O(n) work to keep up).

Fenwick Trees allow you to update and query in O(log n), and how it works is really cool and simple. It's really well explained in Fenwick's original paper, freely available here:

http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol24/issue3/spe884.pdf

Its father, the RQM tree is also very cool: It allows you to keep info about the minimum element between two indexes of the vector, and it also works in O(log n) update and query. I like to teach first the RQM and then the Fenwick Tree.

eordano
+5  A: 

2-3 Finger Trees by Hinze and Paterson are a great functional data structure swiss-army knife with great asymptotics for a wide range of operations. While complex, they are much simpler than the imperative structures by Persistent lists with catenation via recursive slow-down by Kaplan and Tarjan that preceded them.

They work as a catenable deque with O(1) access to either end, O(log min(n,m)) append, and provide O(log min(n,length - n)) indexing with direct access to a monoidal prefix sum over any portion of the sequence.

Implementations exist in Haskell, Coq, F#, Scala, Java, C, Clojure, C# and other languages.

You can use them to implement priority search queues, interval maps, ropes with fast head access, maps, sets, catenable sequences or pretty much any structure where you can phrase it as collecting a monoidal result over a quickly catenable/indexable sequence.

I also have some slides describing their derivation and use.

Edward Kmett
+6  A: 

Bootstrapped skew-binomial heaps by Gerth Stølting Brodal and Chris Okasaki:

Despite their long name, they provide asymptotically optimal heap operations, even in a function setting.

  • O(1) size, union, insert, minimum
  • O(log n) deleteMin

Note that union takes O(1) rather than O(log n) time unlike the more well-known heaps that are commonly covered in data structure textbooks, such as leftist heaps. And unlike Fibonacci heaps, those asymptotics are worst-case, rather than amortized, even if used persistently!

There are multiple implementations in Haskell.

They were jointly derived by Brodal and Okasaki, after Brodal came up with an imperative heap with the same asymptotics.

Edward Kmett
+2  A: 

I sometimes use Inversion LIsts to store ranges, and they are often used to store character classes in regular expressions. See for example http://www.ibm.com/developerworks/linux/library/l-cpinv.html

Another nice use case is for weighted random decisions. Suppose you have a list of symbols and associated probabilites, and you want to pick them at random according to these probabilities

   a => 0.1
   b => 0.5
   c => 0.4

Then you do a running sum of all the probabilities:

  (0.1, 0.6, 1.0)

This is your inversion list. You generate a random number between 0 and 1, and find the index of the next higher entry in the list. You can do that with a binary search, because it's sorted. Once you've got the index, you can look up the symbol in the original list.

If you have n symbols, you have O(n) preparation time, and then O(log(n)) acess time for each randomly chosen symbol - independently of the distribution of weights.

A variation of inversion lists uses negative numbers to indicate the endpoint of ranges, which makes it easy to count how many ranges overlap at a certain point. See http://www.perlmonks.org/index.pl?node_id=841368 for an example.

moritz
+7  A: 

Work Stealing Queue

Lock-free data structure for dividing the work equaly among multiple threads http://stackoverflow.com/questions/2101789/implementation-of-a-work-stealing-queue-in-c-c

tintor
+2  A: 

B* tree

It's a variety of B-tree that is efficient for searching at the cost of a more expensive insertion.

karlphillip