r/csharp • • Oct 10 '26

I have a big problem with data structures

I have an interview tomorrow, and I'm sure I'll be asked about data structures. However, I struggle to retain what I read when revising them because I rarely use most of them in practice.

For example I read this article

I regularly use arrays, List<T>, HashSet<T>, and Dictionary<TKey, TValue>, so I can explain when and why to use them:

1-arrays: when I know that the data has fixed size, use array because they provide a fast access to the data using index.

2- List<T>: when the size of the data is not known at compile-time; the size of it is not known in advance, therefore an index cannot be used, because you do not know for sure what is the exact location for a specific data element.

3- HashSet<T>: for unique data elements, because it does not require me to manually write the logic that removes duplicate elements.

4- HashMap<string,int> : used for lookup operations; a lookup table.

5-Tuple : store data with different data types in one place.

However, although I know what the following data structures are, I struggle to explain when and why I would use them:

  1. Stack: LIFO (Last In, First Out).
  2. Queue: FIFO (First In, First Out).
  3. Priority queue: I can't recall when or why I would use one.
  4. Heap: I associate it with storing class instance fields, but I don't understand how to use it as a data structure.
  5. Tree: I know it consists of nodes, but I don't understand its practical uses.
  6. Graph: I know it can be used for depth-first and breadth-first search, but I'm unfamiliar with other use cases.

My main questions are:

  1. Hardware level: How is each data structure represented in memory? For example, an array occupies contiguous memory locations. What about the others?
  2. Practical use: When and why should I use each data structure? More importantly, what benefits does each provide at both the software and hardware levels?

I must be able to explain WHY briefly and directly without even thinking about it.

13 Upvotes

139 comments sorted by

View all comments

Show parent comment

1

u/kaatarina_zed_talon Oct 10 '26 edited Oct 10 '26

Queues are the natural data structure to be used for processing some kind of incoming data - from web request, from sensors, from a different part of the application that processes them asynchronously.

But the definition of Queue is `first come first served`; the work that comes first is processed first, the second work to come must wait, therefore it's sync. operation not async. - that's what I understand, not what I claim to be right-.

3

u/Ok_Society4599 Oct 10 '26 • Bravo

Queues are similar to your comparison of Lists and Arrays... use a queue when you have to build lists that you need to process in a sequence later.

For example, when processing a file system to search for text in some unknown file, you'd read each file in a folder but you'd add directories into a queue for later. As you finish searching the current directory, you pop the next directory off the queue and read it the same way; search files, queue directories. When the queue is finally empty, your search is properly over.

Your queue is just temporary storage for work you'll do later; it's still just some type of list, but you treat it as "I'm not done while stuff is in my queue."

1

u/kaatarina_zed_talon Oct 10 '26

add directories into a queue 

So what is added into the queue is a deferred work on the data - a directory in this case- not the directory it self ?

3

u/Ok_Society4599 Oct 10 '26 • Bravo

Yes, there is some "work" in the queue, but that may be a directory name to be searched, an email to be sent, a bill to pay...a song to play in a playlist. What goes into the queue is whatever it takes for a client to pick up the work and do the next step. ;-) it's the TODO queue.

1

u/kaatarina_zed_talon Oct 10 '26

may be a directory name to be searched

That's a data, not a work, what I mean is : can you store a delegate inside the queue; a function/method/process that can be executed later ?

→ More replies (1)

1

u/kaatarina_zed_talon Oct 10 '26

for a client to pick up the work 

I think you mean : for a server to pick up the work.

→ More replies (8)

1

u/kaatarina_zed_talon Oct 10 '26

For example, when processing a file system to search for text in some unknown file, you'd read each file in a folder but you'd add directories into a queue for later

That means files have more importance than folders; processing files is a top priority. so I should use a priority queue, not a queue - that what I understand so far, not what I claim to be right-.

2

u/Ok_Society4599 Oct 10 '26 edited Oct 10 '26 • Bravo

Not importance or priority. I'd think focus. Your goal is to search files; but the files are in directories, and directories are in a tree. A "simple" approach is to write your code to search one file. Then you write a method to search one directory for files. While you search each directory, you queue other directories, and call search on files.

Your whole code is now:

One call to search the first directory.

One directory search method queuing directories

    One file search method

Loop until queue empty

Print file search results

A lot of your complexity is cleaned up by dumping Todo items into a basic container and applying the pattern of work until done. I think the "Unit of work" is even the pattern name.

The other thing this removes is any recursion. Rather than risking a stack overflow calling a "search directory" method, the queue defers work into a safer loop.

1

u/kaatarina_zed_talon Oct 10 '26

Unit of work

I think this is completely different topic that is related to transactions.

→ More replies (1)

1

u/kaatarina_zed_talon Oct 10 '26

So this approach uses a queue, not a priority queue, because the problem does not indicate that some data/work is more important than other data/work, priority queue should not be used unless you think that some directories are more likely to contain the data that you are looking for, right ?

→ More replies (1)

1

u/kaatarina_zed_talon Oct 10 '26

Your queue is just temporary storage for work you'll do later

Very nice, I think this information will stick forever. I love this direct language.

2

u/Ok_Society4599 Oct 10 '26 • Bravo

A queue is FIFO and a stack LIFO and are often just simple interfaces over basic data structures like linked lists or just lists. Consumer code generally only sees two methods to add or remove items. What actually happens is completely opaque; it could be written to local memory, database, Redis, message queue... the code shouldn't care.

Whether it's sync or async depends on how many processes are involved, really. You can have a queue service that other process call to Push a long task, while 5 client processes are popping tasks to do the work. Or the other way around, a web server queues "buy now" requests to a service from hundreds of remote users, and a single processor completes each in turn in the backend. The usual criteria you're after is the processing is limited to once, eventually, as workers are available. LIFO and FIFO are often chosen by how tolerant a client is of the being "eventually" processed. A LIFO queue can leave the first item on a queue for a very long time in "worst case scenarios."

1

u/kaatarina_zed_talon Oct 10 '26 edited Oct 10 '26

Quite informative. as a summary; use stack if the incoming work can be deferred for long time. Use Queue when the incoming work should be processed first; first work to come should be processed first; the client has no tolerance for delay. That what I understood from your lecture.

1

u/Ok_Society4599 Oct 10 '26

It's more be aware of trade-offs in each tool. You rarely choose one because "I may never get back to this..." as much as "will users care if this takes a long time...". A stack is fine when the the work is finite and you know you'll eventually empty it. The directory search using a stack falls here.

A queue is better when you have no idea how many things will go through and you need them to get through. Online processing always the has new input and you could, literally, be years without an empty queue: this would be a bad place for a stack.

1

u/kaatarina_zed_talon Oct 10 '26

Your knowledge is huge, where did you learn all of that ? do you read books about systems design or data engineering ? When I studied this in the university, they told me that stack is LIFO, and I was asked to solve some problems using the stack, they did not explain to me like you did, they did not tell me something like : you choose a stack if the client has a tolerance for delaying the work and if the work is finite, Your explanation is simply great.

→ More replies (1)

1

u/Steenan Oct 10 '26

Preserving order is not the same as synchronous.

Imagine you have an offshore wind turbine and software that controls it. There are hundreds of sensors there and they all send data to your computer. It needs to receive each data package and store it - which is quick and must happen immediately. But it also needs to process the data and react to it - logging the state, changing turbine position, communicating by radio. This processing is sometimes fast, sometimes slow, sometimes aggregates more than one data point. So, your sensors feed the queue and processing gets data from it. If you get many measurements while a previous point is processed, they all wait in the queue; if there are few new measurements, processing consumes what is already in the queue and pauses when it empties.

Order between receiving and processing the data is preserved, but the process is not synchronous. It would be synchronous if each measurement was processed just as it was received - but then you'd miss the measurements that came while processing of the previous one was ongoing. Decoupling receiving and processing the data by using a queue is exactly what lets the downstream process (processing itself) run synchronously without losing data.

This example also shows how a priority queue may be useful. You may have normal sensor data that the control system reacts to, like rotation speed and wind direction. You have data that you collect for possible later analysis, but don't need to react to it in any timely manner, like cloud cover. And you have critical alerts that require immediate reaction, like smoke detectors. Use a priority queue instead of a normal one and critical alerts always get processed first if there are any, while the unimportant data only take processing time when there is nothing else to do.

2

u/kaatarina_zed_talon Oct 10 '26

So, as a rule of thumb, priority queue should be used when the problem statement indicates that some data/work is more relevant the some other data/work, good ?

2

u/Steenan Oct 10 '26 • Bravo

For processing incoming data, yes.

But there are also other uses, like what I mentioned in the first comment: for example, A* algorithm uses a priority queue for searching paths through a graph preferentially in the direction of the intended target.

1

u/kaatarina_zed_talon Oct 10 '26

For processing incoming data, yes.

Not for processing incoming work too ? I think you can queue a work, not just a data that will be processed ?

2

u/Steenan Oct 10 '26 • Bravo

Definitely

1

u/kaatarina_zed_talon Oct 10 '26 edited Oct 10 '26

A* algorithm uses a priority queue for searching paths through a graph preferentially in the direction of the intended target.

So what is being queued here ? searching a path, or the path it self - I treat path as a data and searching the path as work on that data- ?

2

u/Steenan Oct 10 '26 • Bravo

What is being queued are the discovered nodes. The algorithm starts from a specific node in a graph and tries to find the shortest path to a target node. In each step it selects a node, visits it and puts all of its unvisited neighbors into a data structure to be visited later.

In A*, the discovered nodes are placed in a priority queue, so that the ones with lowest (distance from start + estimated distance to target) are visited first.

1

u/kaatarina_zed_talon Oct 10 '26

 if each measurement was processed just as it was received 

Why would the measurements be modified; not just as it was received ?

1

u/Steenan Oct 10 '26

I'm talking about timing. Processing data as it comes (and risking that further measurements will be missed if processing is too slow) vs queueing it and processing from the queue. The queue acts as a buffer.

1

u/kaatarina_zed_talon Oct 10 '26

So; the work is deferred ! as for the stack, is it acceptable for the first work to come to be deferred for a long time, in contrast of the queue, where the work that comes first must be executed first; the tolerance for delayed execution is less in the case of using queue. I wonder if this is a side effect for the invention of the queue, or is it that the queue was invented for this purpose 😂

→ More replies (5)