How do you choose between an array, set, map, stack and queue in a coding exercise?
Answer
Choose from the operations the problem needs. Arrays preserve indexed order, sets provide uniqueness and membership, maps associate keys with values or counts, stacks support last-in-first-out traversal, and queues support first-in-first-out work. Explain expected lookup, insertion, deletion and ordering costs, then test empty, duplicate and boundary cases for the chosen structure.
Strong answer includes
- chooses from required operations rather than habit
- explains ordering and complexity tradeoffs
- tests empty and duplicate inputs
Practical example
Asked to implement an LRU cache, a candidate who reaches for a plain array first has to redesign mid-interview once eviction requires O(1) removal from the middle; combining a hash map with a doubly linked list from the start gets both O(1) lookup and O(1) eviction.