
Choosing the right data structure is often the most critical part of solving any DSA interview problem. It directly impacts your solution’s time and space efficiency. In interviews, your ability to map problem constraints to the correct data structure is a strong indicator of your depth in computer science fundamentals.
Key Questions to Ask Yourself
- Do I need fast access or lookup? → Use
HashMap
orHashSet
. - Do I need to maintain insertion order? → Use
Array
orLinkedList
. - Do I need sorted access or range queries? → Use
TreeMap
orBalanced BST
. - Do I need to access front/rear efficiently? → Use
Deque
. - Do I need the most/least recent element? → Use
Stack
orQueue
. - Do I need to find min/max frequently? → Use
PriorityQueue (Heap)
. - Do I need to perform a lot of insertions/deletions? → Use
LinkedList
. - Am I working with sequences or index-based access? → Use
Array
orList
.
Common Data Structure Choices
1. Array
An array is a basic linear data structure that stores elements at contiguous memory locations. Each element is identified by an index, starting from 0. Arrays are ideal when you know how many elements you'll store and when you need to frequently access items by their position.
When to Use:
- You need fast access using indices (e.g.,
arr[4]
gives 5th element instantly). - Number of elements is fixed or changes infrequently.
- Insertion and deletion are not frequent or mostly at the end.
Examples:
- Storing daily temperatures, exam scores, or product IDs.
- Implementing sliding window problems or prefix sum arrays.
Time Complexities:
- Access: O(1)
- Insert/Delete (at end): O(1) in dynamic arrays
- Insert/Delete (at beginning/middle): O(N)
2. HashMap / HashSet
A HashMap stores key-value pairs, while a HashSet stores only unique keys. They both use a technique called hashing to store and retrieve values in constant time (on average).
When to Use:
- You want to count frequencies of elements (e.g., word count).
- You need to check presence of an element quickly.
- You want to eliminate duplicates (use
HashSet
).
Examples:
- Find the first non-repeating character in a string.
- Detect if a pair exists with a given sum (via complement lookup).
Time Complexities:
- Insert: O(1)
- Delete: O(1)
- Search: O(1)
Note: In worst cases (due to hash collisions), performance can degrade to O(N), but this is rare in practice.
3. Stack
A stack is a linear data structure that follows the Last-In First-Out (LIFO) principle. The last element inserted is the first to be removed — like a pile of plates.
When to Use:
- You need to reverse a sequence (e.g., undo history).
- You want to manage nested operations (like function calls).
- You need to validate balanced brackets or syntax.
Examples:
- Implementing backspace operations in text editors.
- Parsing HTML tags or mathematical expressions.
Time Complexities:
- Push (insert): O(1)
- Pop (remove): O(1)
- Peek (view top): O(1)
4. Queue / Deque
A queue works on First-In First-Out (FIFO) principle — the first element inserted is the first one removed. A deque (double-ended queue) allows insertions and deletions from both ends.
When to Use:
- You need to maintain the order of processing (e.g., task queues).
- You want fast access and modifications at both ends (Deque).
- You are implementing level-order traversal (BFS) or sliding window.
Examples:
- Customer service line (queue).
- Sliding window maximum (deque).
Time Complexities:
- Enqueue / Dequeue: O(1)
- Front / Rear Access: O(1)
5. PriorityQueue (Heap)
A priority queue (usually implemented as a heap) allows you to always access the element with the highest (or lowest) priority. It’s useful when the order of processing depends on priority rather than arrival time.
When to Use:
- You need to keep retrieving the smallest or largest element quickly.
- You are solving a problem with “top K” or scheduling requirements.
Examples:
- Finding top 3 largest elements in a stream.
- Implementing Dijkstra's algorithm for shortest paths.
Time Complexities (Min/Max Heap):
- Insert: O(log N)
- Delete (min/max): O(log N)
- Access min/max: O(1)
6. TreeMap / TreeSet
A TreeMap is a map that maintains keys in sorted order, backed by a self-balancing BST (like Red-Black Tree). A TreeSet is the sorted version of a HashSet.
When to Use:
- You need to store elements in a sorted fashion.
- You need fast access to floor, ceiling, or range of elements.
Examples:
- Finding the closest value smaller than or greater than a target.
- Efficient interval merging or searching.
Time Complexities:
- Insert: O(log N)
- Delete: O(log N)
- Search / floor / ceiling: O(log N)
7. LinkedList
A LinkedList is a linear data structure where elements are stored in nodes, and each node points to the next one. Unlike arrays, linked lists do not store data contiguously in memory.
When to Use:
- You have frequent insertions and deletions, especially at the head or tail.
- You don’t need random access (like
arr[i]
).
Examples:
- Implementing a stack or queue from scratch.
- Deleting a node in O(1) time when pointer to the node is given.
Time Complexities:
- Insert/Delete at head/tail: O(1)
- Search or access by index: O(N)
Example-Based Heuristics
Problem 1
Problem Statement: Find the first non-repeating character in a string.
Data Structure Choice: HashMap + Queue
Justification: Use a HashMap to store character frequencies and a Queue to maintain the insertion order for tracking the first unique character efficiently.
Problem 2
Problem Statement: Validate if a string has balanced parentheses.
Data Structure Choice: Stack
Justification: Stack is ideal for checking balance in nested structures by storing opening brackets and ensuring correct closing match.
Problem 3
Problem Statement: Find the top K frequent elements in an array.
Data Structure Choice: HashMap + Min Heap
Justification: HashMap tracks frequency counts, and Min Heap maintains top K elements in O(log K) time per insertion.
Problem 4
Problem Statement: Implement an LRU (Least Recently Used) Cache.
Data Structure Choice: HashMap + Doubly Linked List
Justification: HashMap provides O(1) access, and Doubly Linked List maintains usage order for efficient eviction.
Problem 5
Problem Statement: Merge K sorted linked lists into a single sorted list.
Data Structure Choice: Min Heap (PriorityQueue)
Justification: Min Heap efficiently keeps track of the smallest current node from each list, allowing optimal merge in O(N log K) time.
Problem 6
Problem Statement: Detect a loop in a linked list.
Data Structure Choice: Floyd’s Cycle Detection (Tortoise and Hare)
Justification: Use two pointers moving at different speeds to detect cycles without extra space.
Problem 7
Problem Statement: Check if two strings are anagrams.
Data Structure Choice: HashMap / Array[26]
Justification: Use a HashMap or fixed-size array to count characters and compare frequencies.
Problem 8
Problem Statement: Find the longest substring without repeating characters.
Data Structure Choice: Sliding Window + HashSet
Justification: Use a sliding window to track unique characters and a HashSet to ensure no repetition.
Problem 9
Problem Statement: Perform level-order traversal of a binary tree.
Data Structure Choice: Queue
Justification: Queue helps in processing each level of the binary tree in FIFO order.
Problem 10
Problem Statement: Find the median in a data stream.
Data Structure Choice: Min Heap + Max Heap
Justification: Two heaps help maintain the lower and upper halves of the stream for median calculation in log time.
Problem 11
Problem Statement: Find the nearest smaller element to the left for each element.
Data Structure Choice: Stack
Justification: A monotonic stack efficiently tracks previous smaller elements in O(N).
Problem 12
Problem Statement: Evaluate a postfix expression.
Data Structure Choice: Stack
Justification: Stack stores operands; operators pop operands, apply them, and push the result back.
Problem 13
Problem Statement: Clone a linked list with random pointers.
Data Structure Choice: HashMap
Justification: HashMap maps original nodes to cloned nodes to handle random pointers correctly.
Problem 14
Problem Statement: Check if a binary tree is symmetric.
Data Structure Choice: Queue / Recursion
Justification: Use a queue or recursion to check mirror-image structure level by level or node by node.
Problem 15
Problem Statement: Find all subsets of a given set.
Data Structure Choice: Backtracking / Bitmasking
Justification: Use recursion or bitmasks to generate all 2^N possible combinations.
Final Tips
- Understand the expected operations and frequency of each.
- Prioritize access patterns (random, sequential, sorted, etc).
- Consider space complexity when using extra data structures.
- When in doubt, clarify the constraints with the interviewer.
Pro Tip: Practice classifying at least 100+ problems by data structure used — this builds natural intuition for interviews.