🧠 Data Structure Coding Questions with Examples and Answers (Part 3)
If you’re preparing for a technical interview, knowing the concepts alone is not enough — you must be able to write code that uses data structures effectively.
In this article, we’ll go through top coding questions with explanations and examples in simple language.
1. Write a Program to Reverse a String Using Stack
Concept Used: Stack follows LIFO (Last In, First Out) — the last character pushed will be the first popped.
Code (Python Example):
def reverse_string(s):
stack = []
for char in s:
stack.append(char)
rev = ""
while stack:
rev += stack.pop()
return rev
print(reverse_string("GLIMSY"))
Output:
YSMILG
✅ Explanation:
We push all characters into a stack and pop them one by one to get the reverse order.
2. Implement Stack Using Array
Concept Used: Stack operations — push(), pop(), and peek().
Code (Python Example):
class Stack:
def __init__(self):
self.stack = []
def push(self, data):
self.stack.append(data)
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.stack[-1]
return None
def is_empty(self):
return len(self.stack) == 0
s = Stack()
s.push(10)
s.push(20)
s.push(30)
print("Top element:", s.peek())
print("Removed:", s.pop())
print("After pop:", s.stack)
Output:
Top element: 30
Removed: 30
After pop: [10, 20]
✅ Explanation:
The list acts as a dynamic array to simulate stack behavior.
3. Implement Queue Using Linked List
Concept Used: Queue works on FIFO (First In, First Out) principle.
Code (Python Example):
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, data):
new_node = Node(data)
if self.rear is None:
self.front = self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if self.front is None:
return "Queue is empty"
temp = self.front
self.front = temp.next
if self.front is None:
self.rear = None
return temp.data
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print("Removed:", q.dequeue())
Output:
Removed: 10
✅ Explanation:
We use a linked list to connect nodes. The front node is removed first — just like a real queue.
4. Find the Middle Element of a Linked List
Concept Used: Two-pointer technique – a fast pointer moves 2 steps, a slow one moves 1 step.
Code:
class Node:
def __init__(self, data):
self.data = data
self.next = None
def find_middle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.data
# Create linked list: 1->2->3->4->5
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
print("Middle element:", find_middle(head))
Output:
Middle element: 3
✅ Explanation:
Fast pointer moves twice as fast as the slow pointer, so when fast reaches the end, slow is at the middle.
5. Check if a String is a Palindrome Using Stack
Concept: A palindrome reads the same forward and backward.
Code:
def is_palindrome(s):
stack = []
for char in s:
stack.append(char)
rev = ""
while stack:
rev += stack.pop()
return s == rev
print(is_palindrome("madam"))
print(is_palindrome("hello"))
Output:
True
False
✅ Explanation:
We reverse the string using a stack and compare it with the original one.
6. Implement a Binary Search Tree (BST) and Inorder Traversal
Concept Used: In a BST, left child < root < right child.
Code:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(root, data):
if root is None:
return Node(data)
if data < root.data:
root.left = insert(root.left, data)
else:
root.right = insert(root.right, data)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
root = None
root = insert(root, 50)
insert(root, 30)
insert(root, 70)
insert(root, 20)
insert(root, 40)
insert(root, 60)
insert(root, 80)
print("Inorder Traversal of BST:")
inorder(root)
Output:
Inorder Traversal of BST:
20 30 40 50 60 70 80
✅ Explanation:
Inorder traversal gives elements in sorted order for BST.
7. Find the Maximum Element in a Binary Tree
Code:
def find_max(root):
if root is None:
return float('-inf')
res = root.data
left_max = find_max(root.left)
right_max = find_max(root.right)
return max(res, left_max, right_max)
✅ Explanation:
Recursively compare the root with the maximum of left and right subtrees.
8. Find the Height of a Binary Tree
Code:
def height(root):
if root is None:
return 0
return 1 + max(height(root.left), height(root.right))
✅ Explanation:
The height is 1 + the maximum of left and right subtree heights.
9. Check for Balanced Parentheses Using Stack
Concept: Stack keeps track of opening and closing brackets.
Code:
def is_balanced(expr):
stack = []
for ch in expr:
if ch in "({[":
stack.append(ch)
else:
if not stack:
return False
top = stack.pop()
if (top == '(' and ch != ')') or (top == '{' and ch != '}') or (top == '[' and ch != ']'):
return False
return not stack
print(is_balanced("{[()]}"))
print(is_balanced("{[(])}"))
Output:
True
False
✅ Explanation:
Each opening bracket must match a corresponding closing one in order.
10. Implement Queue Using Two Stacks
Concept Used:
One stack for enqueue, another for dequeue.
Code:
class QueueUsingStacks:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, data):
self.stack1.append(data)
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
if not self.stack2:
return "Queue is empty"
return self.stack2.pop()
q = QueueUsingStacks()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print(q.dequeue())
print(q.dequeue())
Output:
10
20
✅ Explanation:
We use two stacks — one for adding elements and another for removing them in correct order.
11. Find Duplicate Elements in an Array Using Hashing
Code:
def find_duplicates(arr):
seen = set()
duplicates = []
for num in arr:
if num in seen:
duplicates.append(num)
else:
seen.add(num)
return duplicates
print(find_duplicates([1, 2, 3, 2, 4, 1]))
Output:
[2, 1]
✅ Explanation:
We use a set to track seen elements — duplicates appear twice.
12. Find the Intersection of Two Arrays
Code:
def intersection(arr1, arr2):
return list(set(arr1) & set(arr2))
print(intersection([1,2,3,4], [3,4,5,6]))
Output:
[3, 4]
✅ Explanation:
We use set intersection to find common elements.
Conclusion
Practicing coding questions like these helps you master the logic behind data structures.
Start small, understand how each structure works, and then combine multiple structures (like using stack and queue together) to solve real-world problems.
The more you practice, the faster and more confident you’ll become in interviews!