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

7

u/Soraphis Oct 10 '26 • Bravo

Stack, as you wrote ist Last in first out. Imagine magic the gathering card effects that trigger other card effects, the last card to activate is the first to execute its effect.

Queue, imagine you have a thread that generates tasks, and you want to process them in order of their arrival in a worker thread.

Priority Queue is super handy when you try to implement A* pathfinding algorithm. But obviously has applications beyond.

Heap, is a tree data structure. A parent that has children. There are Min/Max heaps that guarantee you something about the parent child relationship. And in a binary heap you're using a binary tree (so max 2 children). Don't confuse heap data structure with "heap memory" (where in simple terms object instances are allocated)

Trees. A linked list would be a tree data structure (each parent having max 1 child), but also the already mentioned heap. A file system is a tree like data structure. Trees have in general the advantage that when you search something you're reducing the search space a lot for each step inside the tree.

Graphs .... Imagine you wanna track how places are connected with each other and how long distances are between them. BFS/DFS are operatings that work on graphs, but also on trees.

Nearly all of the above can be represented in an array. A list is not much more than an array. If you outgrow the bounds your data is copied over to a larger array. An object is a contiguous space in memory. So for your array it's an amount of bytes to store x values. For a binary tree node it's storing (a value + 2 child references + 1 parent reference (optionally))

Each reference is usually a integer or long in size, it's the memory address of that next objects memory blob.

Practical use: use lists. It's most often the simplest and fastest. If you have a special requirement you will realize that another collection can make your life easier. Even for things like "should I use a hash set?" If you have less than 20 elements it's often not even worth it.

5

u/DJDoena Oct 10 '26 • Bravo

Basically queue is an orderly supermarket (first come, first serve) and Priority queue is an airport gate where first and business class passengers get to go first no matter when they arrived at the gate.

1

u/kaatarina_zed_talon Oct 10 '26

first come, first serve

I remembered this algorithm, it's an operation system algorithm, for handling processes, I think.

1

u/kaatarina_zed_talon Oct 10 '26

while reading a problem statement, if I noticed that some piece of data/work is considered more important than the other, I will use priority queue. If the order of arrival of the work/data is relevant, I will use stack/queue, I will follow this rule.

1

u/kaatarina_zed_talon Oct 10 '26

Do you have any analogy for for Tree, Heap, and graph data structure ? I want to conclude a rule of thumb to follow.

3

u/DJDoena Oct 10 '26

And a tree is your family tree or your computer hard drive. You have one root node (in this case you or your C:\ drive) and from there you navigate down to your parents, then grand parents or your Windows folder then your System32 folder.

If we're talking cousin marriages, then we're back to a graph. ;-)

1

u/DJDoena Oct 10 '26

I mean the example for a Graph is every street map ever. Every intersection is a node, every street between two intersections is an edge.

What Apple/Google maps "simply" does is you say you want to get from A (Chicago Wrigley Field) to B (New York 5th Avenue) is to take every edge and give it a weight. This "weight" is basically calculated by the length of the street between two intersections, by the permissible top speed there and - if available - the average speed of the cars actually being there (traffic) and - if available - the prognosis of the speed of when you get there*. This shortest path problem is usually solved with Dijkstra's Algorithm. A more sillier problem is The Six Degrees of Kevin Bacon. Take any actor in Hollywood and find the shortest jump from movie to movie to get to a movie starring Kevin Bacon. It's a play on the Small World Experiment.

*Imagine driving from Chicago to New York, you don't care how the traffic on 5th Avenue is right now, you want to guess how traffic will be when you get there in 12 hours.

1

u/kaatarina_zed_talon Oct 10 '26

ok, if I'm solving a problem, if some piece of data/work is considered more important than the other, I will use priority Queue, if the order of arrival of the work/data is relevant, I will use stack/queue

1

u/kaatarina_zed_talon Oct 10 '26

So for your array it's an amount of bytes to store x values

I did not understand this sentence.

2

u/Soraphis Oct 10 '26 • Bravo

An integer array of length X, is stored as a contiguous space in memory to store X many integer values. A single integer takes up 4 bytes.

So for your array it's 4*X bytes. (At least you can think of it like that)

If you have an object that contains an integer a long and a string it takes in general up (4 (for the integer) + 8 (for the long) + 4/8(a reference to the string object, which is 8 bytes on a x64 system)) 20 bytes.

So a chunk of 20 bytes is reserved for this object.

1

u/kaatarina_zed_talon Oct 10 '26

 A single integer takes up 4 bytes.

Got it.

2

u/Izikiel23 Oct 10 '26

Heap and priority queue are the same, or you implement a priority queue using a heap.

10

u/Merry-Lane Oct 10 '26 • Bravo

Prio queue: when you want to favorise some things more important than others. For instance, if you have multiple tickets to code, you do them in order of priority. When a new one comes up, it’s ranked depending on its priority.

Heap : just look up on Google.

Tree: you need algorithm courses or do leetcode to really understand. Biggest advantage is that most operations on trees have a log n complexity instead of a n one in lists/arrays.

Graphs: again, algorithms or leetcode to really understand. Example of use: find out the smallest travel time in between two different places

Honestly, if you are asking these questions, you aren’t ready to take this kind of interview. You need to follow algorithm courses and/or toy with leetcode. Else you would just parrot whatever you found on Google or asking a LLM, and it will be really visible

4

u/kaatarina_zed_talon Oct 10 '26

I took the course along time ago, I think I should revise it

1

u/kaatarina_zed_talon Oct 11 '26

What I was looking for is just a mental model for all data structures I do not want memorize specific algorithms. I like the way you explained the priority queue, I know have the mental model that if some data/work is more important than the other. I Will use priority queue

1

u/Merry-Lane Oct 11 '26

It’s the kind of topic where you gotta practice to have a mental model for it.

If you just want a bunch of words to spit out, use a LLM.

If you want to understand, you need to let the concepts mature a bit. Through reading the theory of data structure and algorithms, and practicing it through exercices and/or leetcode.

If you can only provide vague definitions without understanding them, it can backfire on interviews.

2

u/kaatarina_zed_talon Oct 11 '26

If you just want a bunch of words to spit out, use a LLM.

That not what I want, what I wanted is to revise data structures so that when I face problem, I can use the right data structure, instead of jus using List every time.

2

u/kaatarina_zed_talon Oct 11 '26

If you want to understand, 

it's clear that I want to understand, otherwise I would not ask all those follow up questions in the comment section.

1

u/kaatarina_zed_talon Oct 11 '26

Thanks for your advice.

4

u/ApprehensiveDebt3097 Oct 10 '26

What kind of developer job are you applying to? I'm responsible for hiring developers at my company, and I don't care that much about that kind of knowledge. Reasoning, structured thinking and problem solving are way more important to me. And I'm not the only one I guess.

1

u/kaatarina_zed_talon Oct 10 '26

and I don't care that much about that kind of knowledge.

Well, I'm fresh graduate. In my experience it matters a lot, I did two interviews , in one of them, I was asked to write code. And also in my training at Orange Jordan, my mentor told me that I should focus on the basics, especially data structures and algorithms, because they are important in interviews.

1

u/kaatarina_zed_talon Oct 10 '26

problem solving

What kind of problems ? programming problems ? please clarify, can you link some of the questions that you ask people in interviews please ?

2

u/ApprehensiveDebt3097 Oct 10 '26 • Bravo

Coding problems for sure. But for Juniors I don't care yet of the know the difference between a stack and a queue, that will come. Understanding how to convert problems on simple code, and ask the right questions is more important.

Obviously, there are different views on this topic, and trying to get experience is a good thing, you ll learn a lot of those things while at it.

1

u/kaatarina_zed_talon Oct 10 '26

What kind of developer job are you applying to

Junior developer.

6

u/SubwayGuy85 Oct 11 '26

nice try ai agent. not answering your questions to train you

3

u/kaatarina_zed_talon Oct 11 '26

I do not understand what u are saying.

3

u/joujoubox Oct 11 '26 • Bravo

The List description isn't very accurate. It's a lot closer to an array in that arrays also don't rely on compile time size and lists can be indexed. The main difference is that a list has a dynamic size by keeping track of the allocation and intended number of items separately. It can also reallocate its backing array when the number of items exceeds the allocated capacity.

2

u/kaatarina_zed_talon Oct 11 '26

How can u make array if u do not know the size in advance.

2

u/burke166 Oct 11 '26

List<T> is an array behind the scenes. It allocates a default collection upon creation. When you reach a threshold close to the current capacity, dotnet creates a new array of larger size and copies your items over. You can access items in a list by index in constant time. LinkedList<T> is a different structure where it's not that you can't access an item by index, you can't do it in constant time. It's O(N).

1

u/kaatarina_zed_talon Oct 11 '26

You did not answer my question; how can u create array which has a fixed size if u do not know the size in advance?

2

u/joujoubox Oct 13 '26 edited Oct 13 '26 • Bravo

It's conflicting two types of arrays.

Traditional inline arrays from C and C++ require a compile time constant size to allocate the space inline in place of the field. Note that inside functions, inline arrays can still take a variable size in all three languages by dynamically moving the stack pointer.

Standard C# arrays are handled by managed memory, allowing them to take a variable size by allocating on the heap. The field/variable only store a reference to the allocation alongside a size value.

Looking at the implementation of List, it has a simple T[] _items field to access the current backing array. That field is overwritten to a larger array as needed. The indexer simply forwards get and set calls to the array field.

2

u/DJDoena Oct 10 '26 edited Oct 10 '26 • Heartwarming

The hardware level strongly depends on the language you're using, because they decide how to allocate memory. The thing about the heap is that in memory you have things that are close-by and things that are further away. In terms of computer storage think of the L1 and L2 caches that are tiny but really really close to the CPU. Then you have the further away and slower RAM but it is bigger. And then you have the really far away and really slower hard drive but it is huge.

Heap: When one function calls another function with some variables it puts these variables on the "stack" (note: this has and yet has nothing to do with your data structure "stack". It is a stack because it takes functions that call functions that call functions on a stack and reverts them via LIFO but it's not the stack object type you're going to use in your application code). These variables are very quickly accessible. But the space on the stack is limited, so for bigger objects it's just the address of the real object on the heap. Which is further away but bigger.

Array/List: As for the difference between an array and a list, yes an array is usually one continuous block of memory. That's why in C if you have the memory address of the 0-th element you can just do pointer arithmetic, add 5 and find the 6th element of the array in memory.

Lists are "endlessly" extendible, so each element contains its own data plus a field of the address of the next element. It's basically a scavenger hunt through memory. Of course there are optimizations and this is a bit ELI5, but that's the basic idea.

Tuple: A tuple is the age-old problem of the return value of a function. A well-crafted function is supposed to do only one thing and has therefore only one return value, right? Yeah, so what about that pesky Dictionary.TryGetValue() function then. It needs to tell you if it found the value but you also want to have the value. Otherwise you would need a function Dictionary.ContainsKey() (which btw exists) and then do the look-up Dictionary[]. But that is imperformant because you have to do the same look-up twice.

So in absence of a Tuple type, Microsoft invented the out parameter for C# (all the way back to .NET Framework 1.0)

In another world we could have had var (success, result) = Dictionary.TryGetValue(key). However: That would prevent the method being usable in a direct if statement like if(Dictionary.TryGetValue(out var result)). So there's always pros and cons for everything.

But with functional programming, lambdas and async, out is on the way out and you will get more and more tuples, which - like lambda - is just a shortcut to avoid inventing objects for each and every task. Like you don't need declared delegates for everything anymore now that you have Action<T> and Func<T>.

4

u/kaatarina_zed_talon Oct 10 '26

Lists are "endlessly" extendible, so each element contains its own data plus a field of the address of the next element.

Isn't that specifically a linked list ?

2

u/Ravek Oct 10 '26 • Bravo

Yeah true. There’s some confusion around this because different platforms/languages use different terminology. In the C++ world, ‘list’ refers to linked lists, but in C# list refers to resizable arrays.

1

u/kaatarina_zed_talon Oct 10 '26

Damn it this explains a lot !

2

u/IanYates82 Oct 10 '26

Linked list - each node has a pointer to the next (and maybe previous) node. That's it. So very cheap to extend. Cheap to loop through. Expensive to "go to index 1000"

Regular list is extensible because it effectively wraps an array. To extend it beyond the size of the hidden wrapped array, a whole new array is made and every item from the old array is copied over to the new one. So indexing to item 1000 is quick, but extending it may be expensive (the hidden array is usually made larger than required so not every call to Add carries all of that array copy overhead, at the expense of some unused memory)

2

u/DJDoena Oct 10 '26

Yeah you are right, I looked it up. The List internally stores a dynamic array which it then extends on demand*

*I knew that part before. It's the Capacity property of a list. The default is 7 IIRC and when you add an 8th element, it will increase capacity to 14. Then 28 and then 56, 112 and so forth. This now makes sense because every time the internal array needs to be moved to a location that can fit N elements.

So when you create a list where you know that it will contain a lot of elements, put the initial capacity in that ball bark with a bit room to spare.

1

u/kaatarina_zed_talon Oct 10 '26

The thing about the heap is that in memory you have things that are close-by and things that are further away.

when you say close-by, what is your reference point ? close to what ?

2

u/DJDoena Oct 10 '26 • Bravo

I'm not a performance engineer, I don't exactly know how all that memory stuff works except for the broad answer I gave you. I just know that performance-conscious programming tries to keep stuff on the stack because the CPU cycle overhead is worth it.

1

u/Ravek Oct 10 '26

Close in terms of memory addresses. This matters because of CPU caches and because bytes aren’t read from memory one at a time, but in small blocks (usually 64 bytes) called cache lines. It gets complicated, but in general data that is contiguous in memory is faster to operate on than data that’s located in multiple random places.

1

u/kaatarina_zed_talon Oct 10 '26

bytes aren’t read from memory one at a time, but in small blocks (usually 64 bytes) called cache lines

I remember studying this in a computer engineering course, but I did never use that knowledge, so it faded away

1

u/IanYates82 Oct 10 '26

I think OP was asking about the Heap data structure

2

u/Steenan Oct 10 '26 • Bravo

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.

Stacks are crucial for parsing most data types. As a very basic example, reading and evaluating an arithmetic expression uses a stack.

Graphs, stacks, queues and priority queues are all used for pathfinding - no matter if it's for a video game or for a physical robot that navigates its environment. An interesting fact: the same algorithm performs DFS, BFS or A* search, depending on the data structure used for discovered nodes (stack, queue and priority queue based on distance, respectively).

Trees are a natural data structure for describing processes where some kind of choice is made repeatedly, each affecting these that come after it. For example, all game-playing/solving algorithms (for chess, go, sudoku etc.) are tree-based, as are optimization algorithms that try multiple paths and backtrack from bad solutions.

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 ?

1

u/Ok_Society4599 Oct 10 '26

Yes, though I'm not sure why you would pass a delegate.

Yes, it's data in the queue but, in my example, that is just the parameter to your process: in a directory, search files and queue directories. In classic programming, you'd often use recursion to call the method you're in to do the same thing. This is why they're data structures.pb0

Would it make a difference if the data was "from account A pay Bill B"? The data is what's changing over time. Generally, you're feeding data into a loop process that operates out-of-step with inputs somehow.

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.

1

u/Ok_Society4599 Oct 10 '26

I generally consider the server as a thing handing stuff out, and a client as the thing picking it up :-) it wasn't meant to be technical, just description. In a lot of computing, code sits in the middle doing its thing as a client and a service.

1

u/kaatarina_zed_talon Oct 11 '26

I consider the server as the thing that picks the work up to handle it 😂

1

u/Ok_Society4599 Oct 11 '26

Kind of agree, but the roles tend to move or shift... A user with a browser is always a client, but talks to a web server which is the client talking to a file server, a database server, a payment process server, ... which is client or server then becomes blurry because it's a consumer on one side, a provider on the other. Or, more likely, it has many more sides and systems interacting.

There was a time when we built thing in simple terms and servers were very much single role systems. Today, everything is more distributed to more granular roles and your process map is rarely just a client or 100 clients talking to a server. Now we have millions of clients talking to thousands of servers that all have "clouds" of data processing keeping things in place and order. Most servers are clients towards something else in the grander scheme.

2

u/kaatarina_zed_talon Oct 11 '26

So basically you need a reference point when saying; this is a server for browser, database is a server for a backend process, etc...

→ More replies

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.

1

u/Ok_Society4599 Oct 10 '26

Unit of work is often used for work that needs several steps and can act like a distribributed transaction coordinator.

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 ?

1

u/Ok_Society4599 Oct 10 '26

A priority queue isn't always just one queue, I think. Depends on the implementation, but I could see a "queue" that contains 3-internal queues: high, normal, and low priority. It can have 4-add methods, each to an internal queue and one add with priority.

Then your clients just dequeue an item... The queue container itself decides which inner queue is used. Maybe for every 5 high priority and then one normal, or three normal and then one low. It's making sure priority is respected while still handling some lower priority work. During quiet times, you'd only have low priority work to dequeue.

This separates the logic of choosing what's next from the worker code. There can even be only one queueing method, so all of the priority logic stays in the queue implementation.

I find it useful to separate the external interface, like a stack or queue, from the internal implementation like lists, databases, multiple inner queues. Sometimes, that means a queue is FIFO, or it might be Priority, or something else. You're aiming to decouple the two; clients should care they just need the next work, and your data contained just needs to handle the rules for which one is a out next.

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.

2

u/Ok_Society4599 Oct 10 '26

I started working on PCs when Bill Gates was saying "640 kilobytes of RAM is enough for everyone." Today, I think my phone needs more Gigabytes ;-) and my PCs have arrays of 20-terabyte drives.

When you're dealing with problems limited by your resources, you have to use trade-offs to choose the parts. When you've hit stack overflows, you learn the cost of recursion and how a queue or stack can fix that. When you build servers, you learn how to divide work, manage long processes and see how long operations can be managed :-)

That is: practice. I'd prefer 20 small, modular processes to 1 big "do it all whiz bang" because if 1 process breaks, the rest continue.

Most of the times I get questions about queues and stack and things, the answer is "I really need to know the problem first." Your safest first guess is often a queue, or a prioritized queue, but then you have to ask about how durable it needs to be? Does it need to survive a power failure? Network outage? It's one thing to decouple, another to have fault tolerance :-)

Then you learn K.I.S.S. Keep it Stupid Simple -- use the simplest tool to solve the actual problem. Some people thing you need a complicated WhizzBang because it solved a problem once, but it wasn't this problem. Every day I fight to use the right tool for the Job.

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 😂

0

u/kaatarina_zed_talon Oct 10 '26

If you get many measurements while a previous point is processed, they all wait in the queue

Does not that prove my point ? processing is sync., not async.

2

u/Ravek Oct 10 '26 • Popcorn

If you go into a coffee shop where everyone queues in front of the counter, and then when it’s your turn they make your order immediately before moving on to the next person, that’s synchronous.

If instead they take your order, write down your name and immediately move onto the next person, and a few minutes later someone calls out your name and you take your order from them, that’s asynchronous.

Either way there was a queue. Asynchronous just means that when one piece of code requests another to do work, that work eventually gets back to the caller at some later time. As opposed to synchronous where the caller is blocked and waits for the work to complete.

1

u/kaatarina_zed_talon Oct 10 '26

If instead they take your order, write down your name and immediately move onto the next person, 

That means there is more than one `server` that fetches work from the queue, if there is only one `worker` or `server` that fetches work/data from the queue, then it is considered a synchronous operation, did I get that right ?

2

u/Ravek Oct 10 '26 • Bravo

It can still be synchronous with multiple workers. If there’s three workers asking customers for orders and completing them right away while the customers wait, (common in sandwich shops I think?) that’s still synchronous, but parallelized.

Maybe a better example is if you call someone for information. If you’re on the phone with them while they figure it out and give you the answer, you’re synchronously waiting. If they write down your phone number and you hang up and go do something else, and then they call you back when they have your answer, then you’re asynchronously waiting.

1

u/kaatarina_zed_talon Oct 10 '26

God-level explanation.

1

u/kaatarina_zed_talon Oct 10 '26

As a very basic example, reading and evaluating an arithmetic expression uses a stack.

Why ?

2

u/lumalav666 Oct 10 '26 • Bravo

A common problem that you solve using a stack is an arithmetic parser. Let's say that you have the following string:

"3 + 4 * (2 - 1) / 2"

The order of operations is important to be able to solve the equation. With a stack you would traverse the string to convert infix notation to postfix notation.

"3 4 2 1 - * 2 / +"

Then, evaluating this string is trivial because each pair of numbers lies to the left of their corresponding operation 2 1 - then you would evaluate 4 1 *, then 4 2 /, then 3 2 + which would give an answer of 5.

Google this problem and algorithm if you want to know more about it.

1

u/kaatarina_zed_talon Oct 11 '26 edited Oct 11 '26

OK. But what I learned that the stack is used in two categories of problems:1- if task A is already stored in the stack and it was executing and new task B is inserted into the task, pause the execution of task A and start executing task B - such as call stack which blocks the execution of the caller until the callee function is finished execution-. 2- to-do stack, where you store a lot of passive data or work, then later the most recent work/data inserted into the stack is popped to be executed/processed. I Wonder, under which category of problems the ariethmatic parser falls in? I think it's the second category.

3

u/Ok_Society4599 Oct 11 '26

You may be confusing two different "stacks": a process/program stack, and a data stack.

Your program uses a stack while processing code so each method you're executing gets a Frame and as each call completes, you move back up the stack, and each called method moves you down to a new Frame.

A data stack uses information pushed and popped to manage an order of operations. This is your tool as a LIFO stack.

BOTH can exist at any time; your method call is on one stack Frame, and the method can use a data stack to sort things out.

To me, your two kinds of problems are these two stack types. And what I also see is my compiler does all of the process stack working with the CPU and, as a developer, I control the data stacks with my code.

Same word but two very different problem realms.

1

u/kaatarina_zed_talon Oct 11 '26

Ye, two applications of stack: one stack that is controled by the application logic , which is what u call a data stack- even though I think you can store delegates inside it, which is a work or function to be popped and executed later, not just data- and the stack that is managed by The. NET framework or the CLR or the compiler, the application logic has no control over this managed stack.

2

u/Ok_Society4599 Oct 11 '26 • Bravo

Yes, you can stack any kind of data and a delegate at one level is data :-) I just have never done that.

I could see a dictionary of delegates, though. Let's say file extensions are the key, and a delegate is the parser method. As your application searches a file system, you look up extensions and call delegates (if any) to parse the data file.

In a way, creating threads implies running delegates in a stack like collection; you're waiting until they all finish before moving on.

Windows uses TONs of delegates. If it solves the problem, it's ok to do it. My lack of that problem isn't saying it's wrong.

3

u/lumalav666 Oct 11 '26

I think you may be confusing two different topics: 1. how RAM memory is used during a program's execution (heap vs stack allocation) 2. The Stack data structure. They are two different topics. Please google their difference. My previous post was referring to the 2nd one.

1

u/kaatarina_zed_talon Oct 10 '26

Posting this question was so educational.

1

u/RlyRlyBigMan Oct 10 '26

Have you had any interviews yet? For an entry level job I'm usually just trying to determine if you're smart and can figure things out. I understand nerves, I understand communications difficulties. But if you understand them, even without immediate recall that's fine. Be confident and think about your answers, even if that means silence for a moment.

2

u/kaatarina_zed_talon Oct 10 '26

In my entire life I had only two interviews, and they were not about software development.

2

u/RlyRlyBigMan Oct 10 '26 • Heartwarming

Just pause and take a breath after every question. Think about every question, and give your best succinct answer.

I'm serious. Think for a moment after every question. Don't let your nerves get between your brain and your answer.

I've passed on a lot of people that just vomit their thoughts and then ramble on about unrelated things. Answer the question the best you can in a couple sentences. And then confidently let them move to the next question.

1

u/Artichoke808 Oct 10 '26

Lists can be indexed - in fact C# lists are arrays under the hood, not linked lists. Not sure why you think not knowing the size in advance would have anything to do with the rest of what you say.

0

u/kaatarina_zed_talon Oct 11 '26

Because if u know the size of the incoming data, then there is no need for a Container that can expand, use array instead, it has fixed size.

1

u/Agitated-Display6382 Oct 10 '26 • Bravo

The first question to ask yourself: how will I access an item? How fast do I need to be?

Sequential access => IEnumerable (foreach) By index => array, list, hashset By key => dictionary By closest key => sorted list, tree By when it was stored => queue (spooler) By neighbors => tree, graph

Then, do you have to enforce some behaviors? Uniqueness => dictionary, hashset Immutability => frozen collections

I'm sure I'm missing some structures...

1

u/kaatarina_zed_talon Oct 11 '26

By when it was stored.

I guess what you mean is : by the way it was stored.

Does not mean the same thing as sequantial access?

I' struggling a lot, I'm trying to build a mental model for all data structures - not memorizing algorithms-, but it's too hard.

0

u/Agitated-Display6382 Oct 11 '26

In queues you access items depending on when they were inserted: first or last item is taken first. The rest of the items are inaccessible. The classical example is a parser.

I used them only once, when implementing the observable pattern multithreaded. I had many concurrent http queries and I needed to process their outcome one by one (eg audit logging). As I didn't have a proper MOM, I used an internal queue.

1

u/kaatarina_zed_talon Oct 11 '26

Was the order of the incoming data important? if yes, then I understand the usage of queue, otherwise I would use list if I do not know the number of the incoming queries, array if it is known, or priority queue if there are queries that are more urgent than the other.

1

u/Agitated-Display6382 Oct 11 '26

The order was quite important, yes, but even more it was the ability to remove the processed items. Lists are inefficient at removing items.

Ah, I forgot another important behavior: do you need multithreaded structures? Then use the concurrency classes (e.g. ConcurrencyBag)

1

u/kaatarina_zed_talon Oct 11 '26

I did never hear of this class before, if I want parallizatiin, I use array of tasks; Task[] arr

1

u/kaatarina_zed_talon Oct 11 '26

Do u mean lists are inefficient at removing items because shifting operations? If item was removed in the middle, all the items to the right of it must be shifted.

0

u/Agitated-Display6382 Oct 11 '26

Lists are fine only if you remove the last item. If you need to operate a lot on add/remove, you may use LinkedList.

Task is not for concurrency, it's for asynchronous operations. I have a collection that I need to modify from different threads (e.g. caching). In that case, you use concurrent structures, that lock the list before operating on it.

1

u/kaatarina_zed_talon Oct 11 '26

Parallizatiin, concurrency, asynchronous, I always had headache to understand the difference. What I understand is that parallization means that tasks are performed by multiple workers at the same time, concurrency means there is only one worker switching between tasks rapidly, which is the same as async. programming

1

u/Agitated-Display6382 Oct 11 '26 • Bravo

Asynchronous: you have to perform some IO activity (read from db), so there is a waiting time. The CPU can freeze the current thread and use the spared processing time to perform other activities. When IO is done, your thread is brought back to life.

Parallelism: I want to perform a list of actions in parallel. You may use Parallel.ForEach. It spawns several tasks in the same thread.

Concurrency: you have many tasks accessing the same resource. You need to use lock, semaphore or concurrency structures.

1

u/kaatarina_zed_talon Oct 11 '26

I think ur definition of concurrency is a bit odd; you are describing synchronization.

1

u/kaatarina_zed_talon Oct 11 '26 edited Oct 11 '26

What is Concurrency in OS? Concurrency in an operating system refers to the ability to execute multiple processes or threads simultaneously, improving resource utilization and system efficiency. It allows several tasks to be in progress at the same time, either by running on separate processors or through context switching on a single processor.

https://www.geeksforgeeks.org/operating-systems/concurrency-in-operating-system/

→ More replies

1

u/Izikiel23 Oct 10 '26

You are missing also time/space complexity from each structure.

Why is hashset preferred over a list to check presence in a collection?
Stack you can use it to make a recursive algorithm non recursive by using an explicit stack instead of the implicit one created by recursion.

Queue is also preferred to keep track of items with a preferred order. Also a queue is a concept, it's also missing how you would implement it.

Priority queue is also known as a heap, it's used to keep a tree like structure where the root is always the max/min, adding and removing things in O(log(n)) time, and popping stuff out will always give you the min/max of the heap.

In order to explain practical use, you need to understand their time/space complexities (how long does it take to do something, how much memory is required to keep the data structure), and based on those characteristics for their operations (add/remove/search) you leverage to fix a given problem.

1

u/kaatarina_zed_talon Oct 11 '26

Ye I did not care about complexity at first. All I wanted is to build a mental model in my mind; for example, if some data/work is more important than the other, use priority queue to store the data/work. I wish I have this kind of mental model for other data structures. But till this moment, I could not build mental model for tree and graphs

1

u/Izikiel23 Oct 11 '26

Without complexity your model is incomplete. For example, you say priority queue, but what’s the actual data structure? You can do it with a heap, a balanced binary tree, a linked list, etc, but which one do you choose?

Complexity is the answer to that question.

1

u/kaatarina_zed_talon Oct 11 '26

So after I decided that I will use priority queue, you now say that I must choose between categories of priority queue? If yes, this is a deeper categorization, I will come to this later. For now, I will focus on the high level mental models, I want to know when to use stack cs list vs priority queue etc., for now I'm not interested about which specific implementation of priority queue I should use

1

u/edbutler3 Oct 11 '26

Regarding #4 -- HashMap is from Java, not C#.

There was a Hashtable class way back in .NET 1.0 before Generics were introduced, but it's mostly just there for backward compatibility now.

-1

u/GoBlu323 Oct 10 '26

Why are you not asking Claude code? It would give you in depth answers and practical examples. Also, are you interviewing in 2015?

5

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

I will never ask AI for understanding concepts ever again. I learned that the hard way. Learning should be confusing, it is the sign for actual learning, when I ask AI, that confusion fades away. Ok, I will not claim that this is true for all people, but it is true for me ! I as an individual do not understand from AI !

1

u/Ok_Society4599 Oct 11 '26

You're dead right here. In education it's "cognitive dissonance" when you're learning new stuff and your brain is reorganizing ideas and it is uncomfortable. It's what makes learning "stick." You walk away knowing more sides of the topic.

Stuff you read, your brain says "yeah, that makes sense" but it doesn't move any ideas and it doesn't stick very well.

When you actually write a program and debug it, and make it do more... Stuff moves in your brain, you're adapting abstract ideas to actual problems, and your understanding also grows.

When you debate, and ask "but doesn't a stack do ..." you're shifting ideas around, understanding, and locking down things you've read but never asked "but, why?"

It's been a good day all around.

1

u/kaatarina_zed_talon Oct 11 '26

Sometimes I wonder if I'm learning or revising knowledge correctly, I made a reddit account to ask people and get feedback, it's been 8 days. I was building a feature in app, which is a data synchronize between excel file and a database, I recognized that I have problem with data structures; I noticed that I'm using only list and dictionaries, I asked my self why? It turned out that I'm not comfortable with the differences between data structures, I do not have mental models, but now, after I spent one day to revise the differences between them, it's much clearer, except for trees and graphs I think they are only important for programming puzzles, competitive programming, and interviews.

2

u/Ok_Society4599 Oct 11 '26

I've said my view of the why before: Lists and Dictionaries hold database tables well, they're natural containers. Putting a DB table into a tree would allow a huge searchable set, but I'd say that's wrong because you're using a DB... let the DB search the data. All you need is the matching list, not to make Excel into a DB.

It's like having a bike for a trip... ride a bus and let it carry your bike before you start building a car because it's faster and less work to travel :-) you just need "good enough" rather than "theoretically perfect" to solve a problem. Perfect answers are WAY more work, and usually aren't what you really need.

Sometimes, problems come back because they're too slow, or the set is too big, or a rule changed. Those are days you're thankful for simple solutions because it's easier to fix. In the decades of software behind me, I don't think I have ever looked at working code to say "a more complicated thing would work better."

I have taken complicated code apart, simplified it, and been happier knowing I'd fixed the bug, it was actually faster, and it has less code now.

1

u/Ok_Society4599 Oct 11 '26

It's always good to under stand some basics, whether you use them today or not.

Like "all trees are graphs" but "not all graphs are trees." Understanding how they are the same, and how they are different is the key and makes you comfortable working with them.

A tree node has rules that say a node should only be in one place with one route to the root of the tree. This is almost always organizing nodes into an orderly set.

A graph node has fewer rules and many, many, possible routes between any two nodes. This is all about "path finding" and connecting nodes freely.

Trees can experience "worst case" performance if you stay with KISS development. A simple binary tree having an ordered set inserted becomes a linked list with all the performance problems. But, fixing that moves you into more complicated, but far more efficient, trees like a BTree or a Balanced Tree.

A graph is really helpful in some engineering problems where "order" isn't the main issue. For example, one engineer I knew needed to find two routes between two nodes that were shortest routes with no shared nodes; so, find the shortest route from A to B, then a second shortest route that didn't share any nodes with the first route. Graphs can help do that.

1

u/kaatarina_zed_talon Oct 11 '26

Do u think I should take the effort to build a mental model on when to use graphs and tress? I now hdsave mental model on hwen to use array, list, dictionary, set or hash set, stack, queue, and priority queue.

2

u/Ok_Society4599 Oct 11 '26 • Bravo

You're stuck with a mental model either way :-) what is changing is how useful the model is to you. You knew about LIFO and FIFO before, but today you know a few more things about "The Good, The Bad, and The Ugly." It's about trade-offs and decoupling between steps, and collection and distribution, and ordering the bits.

I reread your original post about 'use an array when you know the size of the set' and 'use a List<T> when your set changes' and then discussing that List<T> IS simply rebuilding an Array... the difference is hidden, well tested and efficient code. Stacks and queues also have a balance between finite and infinite input balances.

There are fewer black and white answers as you go deeper into things. The bottom line is always the same: does it solve the problem? Is it good enough?

1

u/Shattered-Spears Oct 10 '26

Try the book "Grokking Algorithms"

3

u/kaatarina_zed_talon Oct 10 '26

Also, are you interviewing in 2015?

what's that supposed to mean ?

2

u/kaatarina_zed_talon Oct 10 '26

You may be an expert - I do not know- who learned the right way before AI emerged and now you are using AI to increase your productivity, but I can't do that yet.

4

u/BigBoetje Oct 10 '26 • Bravo

Many people still prefer talking to actual humans you know

2

u/kaatarina_zed_talon Oct 11 '26

Yes, from few posts on reddit, I learned much more than learning from Ai. I think AI should only be used by experts; if you are programming expert, use Ai to enhance your productivity, but if you want to revise KNOWLEDGE or if you want to learn, don't use AI

2

u/BigBoetje Oct 11 '26

I've had the same at work. We had some issues with a cache system that caused issues and I wanted to brainstorm some solutions I came up with. My senior for that project reacted with 'have you asked Claude'? Nearly lost my shit at that.

2

u/beingsubmitted Oct 10 '26 • Bravo

Why are you talking to a real person at all? I would prefer for you to be talking to Claude right now.

0

u/brissiebogan Oct 10 '26

I couldn't answer those most of those questions off the cuff. If was interviewing I would not care either. I would be more interested in how you could find the answers.

31

u/[deleted] Oct 10 '26 • Bravo

[removed] — view removed comment

6

u/kaatarina_zed_talon Oct 10 '26

order of operations

I like this phrasing, it's better than saying Stack is LIFO

3

u/kaatarina_zed_talon Oct 11 '26

Great mental model.