Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Proper' collection to use to obtain items in O(1) time in C# .NET?

Something I do often if I'm storing a bunch of string values and I want to be able to find them in O(1) time later is:

foreach (String value in someStringCollection)
{
    someDictionary.Add(value, String.Empty);
}

This way, I can comfortably perform constant-time lookups on these string values later on, such as:

if (someDictionary.containsKey(someKey))
{
    // etc
}

However, I feel like I'm cheating by making the value String.Empty. Is there a more appropriate .NET Collection I should be using?

like image 860
Pandincus Avatar asked Dec 01 '08 14:12

Pandincus


People also ask

Why is the complexity of fetching from an array be O 1 )?

Why the complexity of fetching value is O(1)? As Arrays are allocated contiguously in memory, Fetching a value via an index of the array is an arithmetic operation. All arithmetic operations are done in constant time i.e., O(1).

What data structure has a runtime of O 1?

Only a hash table with a perfect hash function will have a worst-case runtime of O(1).

Which operations on a list L are constant time constant time means O 1?

O(1) — Constant Time Constant time algorithms will always take same amount of time to be executed. The execution time of these algorithm is independent of the size of the input. A good example of O(1) time is accessing a value with an array index. Other examples include: push() and pop() operations on an array.

What does O 1 represent in time complexity for a command?

In short, O(1) means that it takes a constant time, like 14 nanoseconds, or three minutes no matter the amount of data in the set. O(n) means it takes an amount of time linear with the size of the set, so a set twice the size will take twice the time.


1 Answers

If you're using .Net 3.5, try HashSet. If you're not using .Net 3.5, try C5. Otherwise your current method is ok (bool as @leppie suggests is better, or not as @JonSkeet suggests, dun dun dun!).

HashSet<string> stringSet = new HashSet<string>(someStringCollection);

if (stringSet.Contains(someString))
{
    ...
}
like image 102
user7116 Avatar answered Nov 14 '22 22:11

user7116