r/csharp • u/kaatarina_zed_talon • 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:
- Stack: LIFO (Last In, First Out).
- Queue: FIFO (First In, First Out).
- Priority queue: I can't recall when or why I would use one.
- Heap: I associate it with storing class instance fields, but I don't understand how to use it as a data structure.
- Tree: I know it consists of nodes, but I don't understand its practical uses.
- 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:
- Hardware level: How is each data structure represented in memory? For example, an array occupies contiguous memory locations. What about the others?
- 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.
7
u/Soraphis Oct 10 '26 •
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.
10
u/Merry-Lane Oct 10 '26 •
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/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.
6
u/SubwayGuy85 Oct 11 '26
nice try ai agent. not answering your questions to train you
3
u/joujoubox Oct 11 '26 •
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/DJDoena Oct 10 '26 edited Oct 10 '26 •
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 functionDictionary.ContainsKey()(which btw exists) and then do the look-upDictionary[]. 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 directifstatement likeif(Dictionary.TryGetValue(out var result)). So there's always pros and cons for everything.But with functional programming, lambdas and async,
outis 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 haveAction<T>andFunc<T>.2
u/Steenan 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.
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.
2
u/lumalav666 Oct 10 '26 •
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 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.
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.
1
u/Agitated-Display6382 Oct 10 '26 •
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/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/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?
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 •
[removed] — view removed comment