Basic Data Structure Interview Questions For Freshers
Basic Data Structure Interview Questions For Freshers
for Freshers
1. What are Data Structures?
The difference is that the storage structure has data stored in the
memory of the computer system, whereas the file structure has the data
stored in the auxiliary memory.
Some of the main operations provided in the stack data structure are:
push: This adds an item to the top of the stack. The overflow
condition occurs if the stack is full.
pop: This removes the top item of the stack. Underflow condition
occurs if the stack is empty.
top: This returns the top item from the stack.
isEmpty: This returns true if the stack is empty else false.
size: This returns the size of the stack.
A queue is a linear data structure that allows users to store items in a list
in a systematic manner. The items are added to the queue at the rear
end until they are full, at which point they are removed from the queue
from the front. Queues are commonly used in situations where the users
want to hold items for a long period of time, such as during a checkout
process. A good example of a queue is any queue of customers for a
resource where the first consumer is served first.
enqueue(q, data):
While stack1 is not empty:
Push everything from stack1 to stack2.
Push data to stack1
Push everything back to stack1.
deQueue(q):
If stack1 is empty then error else
Pop an item from stack1 and return it
Here, for enqueue operation, the new element is pushed at the top
of stack1. Here, the enqueue operation time complexity is O(1).
In dequeue, if stack2 is empty, all elements from stack1 are moved
to stack2 and top of stack2 is the result. Basically, reversing the list
by pushing to a stack and returning the first enqueued element.
This operation of pushing all elements to a new stack takes O(n)
complexity.
Pseudocode:
o Enqueue: Time complexity: O(1)
enqueue(q, data):
Push data to stack1
dequeue(q):
If both stacks are empty then raise error.
If stack2 is empty:
While stack1 is not empty:
push everything from stack1 to stack2.
Pop the element from stack2 and return it.
push(s, data):
Enqueue data to q2
Dequeue elements one by one from q1 and enqueue to q2.
Swap the names of q1 and q2
pop(s):
dequeue from q1 and return it.
push(s,data):
Enqueue data to q1
pop(s):
Step1: Dequeue every elements except the last element from q1 and
enqueue to q2.
Step2: Dequeue the last item of q1, the dequeued item is stored in
result variable.
Step3: Swap the names of q1 and q2 (for getting updated data after
dequeue)
Step4: Return the result.
A linked list can be thought of as a series of linked nodes (or items) that
are connected by links (or paths). Each link represents an entry into the
linked list, and each entry points to the next node in the sequence. The
order in which nodes are added to the list is determined by the order in
which they are created.
Following are some applications of linked list data structure:
1. Singly Linked List: A singly linked list is a data structure that is used
to store multiple items. The items are linked together using the key. The
key is used to identify the item and is usually a unique identifier. In a
singly linked list, each item is stored in a separate node. The node can
be a single object or it can be a collection of objects. When an item is
added to the list, the node is updated and the new item is added to the
end of the list. When an item is removed from the list, the node that
contains the removed item is deleted and its place is taken by another
node. The key of a singly linked list can be any type of data structure
that can be used to identify an object. For example, it could be an
integer, a string, or even another singly linked list. Singly-linked lists are
useful for storing many different types of data. For example, they are
commonly used to store lists of items such as grocery lists or patient
records. They are also useful for storing data that is time sensitive such
as stock market prices or flight schedules.
2. Doubly Linked List: A doubly linked list is a data structure that
allows for two-way data access such that each node in the list points to
the next node in the list and also points back to its previous node. In a
doubly linked list, each node can be accessed by its address, and the
contents of the node can be accessed by its index. It's ideal for
applications that need to access large amounts of data in a fast manner.
A disadvantage of a doubly linked list is that it is more difficult to
maintain than a single-linked list. In addition, it is more difficult to add
and remove nodes than in a single-linked list.
The key or value object that gets used in the hashmap must
implement equals() and hashcode() method.
The hash code is used when inserting the key object into the map
and the equals method is used when trying to retrieve a value from
the map.
The time complexity is O(1) assuming that the hash function used in the
hash map distributes elements uniformly among the buckets.
Data Structure Interview Questions for
Experienced
24. What is binary tree data structure? What are the
applications for binary trees?
A binary search tree is a data structure that stores items in sorted order.
In a binary search tree, each node stores a key and a value. The key is
used to access the item and the value is used to determine whether the
item is present or not. The key can be any type of value such as an
integer, floating point number, character string, or even a combination of
these types. The value can be any type of items such as an integer,
floating point number, character string, or even a combination of these
types. When a node is added to the tree, its key is used to access the
item stored at that node. When a node is removed from the tree, its key
is used to access the item stored at that node.
A binary search tree is a special type of binary tree that has a specific
order of elements in it. It has three basic qualities:
All elements in the left subtree of a node should have a value less
than or equal to the parent node's value, and
All elements in the right subtree of a node should have a value
greater than or equal to the parent node's value.
Both the left and right subtrees must be binary search trees too.
Following are some applications for binary tree data structure:
Tree traversal is the process of visiting all the nodes of a tree. Since the
root (head) is the first node and all nodes are connected via edges (or
links) we always start with that node. There are three ways which we use
to traverse a tree −
1. Inorder Traversal:
Algorithm:
o Step 1. Traverse the left subtree, i.e., call Inorder(root.left)
o Step 2. Visit the root.
o Step 3. Traverse the right subtree, i.e., call Inorder(root.right)
Inorder traversal in Java:
2. Preorder Traversal:
Algorithm:
o Step 1. Visit the root.
o Step 2. Traverse the left subtree, i.e., call Preorder(root.left)
o Step 3. Traverse the right subtree, i.e., call
Preorder(root.right)
Preorder traversal in Java:
Uses:
o Preorder traversal is commonly used to create a copy of the
tree.
o It is also used to get prefix expression of an expression tree.
3. Postorder Traversal:
Algorithm:
o Step 1. Traverse the left subtree, i.e., call Postorder(root.left)
o Step 2. Traverse the right subtree, i.e., call
Postorder(root.right)
o Step 3. Visit the root.
Postorder traversal in Java:
Uses:
o Postorder traversal is commonly used to delete the tree.
o It is also useful to get the postfix expression of an expression
tree.
2. Adjacency List: In this method, each Node holds a list of Nodes that
are directly connected to that vertex. Each node at the end of the list is
connected with null values to indicate that it is the last node in the list.
This saves space O(|V|+|E|). In the worst-case scenario, a graph can
have C(V, 2) edges, consuming O(V^2) space. It is simpler to add a
vertex. It takes the least amount of time to compute all of a vertex's
neighbours.
One of the cons of this representation is that queries such as "is there an
edge from vertex u to vertex v?" are inefficient and take O (V) in the
worst case.
32. What is the difference between the Breadth First
Search (BFS) and Depth First Search (DFS)?
AVL trees are height balancing binary search trees named after their
inventors Adelson, Velski, and Landis. The AVL tree compares the heights
of the left and right subtrees and ensures that the difference is less than
one. This distinction is known as the Balance Factor.
An AVL tree can balance itself by performing the four rotations listed
below:
Following are some real-time applications for AVL tree data structure:
AVL trees are typically used for in-memory sets and dictionaries.
AVL trees are also widely used in database applications where
there are fewer insertions and deletions but frequent data lookups
are required.
Apart from database applications, it is used in applications that
require improved searching.
The B Tree is a type of m-way tree that is commonly used for disc
access. A B-Tree with order m can only have m-1 keys and m children.
One of the primary reasons for using a B tree is its ability to store a large
number of keys in a single node as well as large key values while
keeping the tree's height relatively small.
Trie is also referred to as the digital tree or the prefix tree. The key to
which a node is connected is determined by its position in the Trie. Trie
allows us to insert and find strings in O(L) time, where L is the length of a
single word. This is clearly faster than BST. Because of how it is
implemented, this is also faster than Hashing. There is no need to
compute a hash function. There is no need to handle collisions (like we
do in open addressing and separate chaining)
Red Black Trees are a type of self-balancing binary search tree. Rudolf
Bayer invented it in 1972 and dubbed it "symmetric binary B-trees."
A red-black tree is a Binary tree in which each node has a colour
attribute, either red or black. By comparing the node colours on any
simple path from the root to a leaf, red-black trees ensure that no path is
more than twice as long as any other, ensuring that the tree is generally
balanced.
Red-black trees are similar to binary trees in that they both store their
data in two's complementary binary formats. However, red-black trees
have one important advantage over binary trees: they are faster to
access. Because red-black trees are so fast to access, they are often
used to store large amounts of data.
Red-black trees can be used to store any type of data that can be
represented as a set of values.
Following are some real-time applications for the Red-Black Tree data
structure:
Max-Heap:
o In a Max-Heap the data element present at the root node
must be the greatest among all the data elements present in
the tree.
o This property should be recursively true for all sub-trees of
that binary tree.
Min-Heap:
o In a Min-Heap the data element present at the root node
must be the smallest (or minimum) among all the data
elements present in the tree.
o This property should be recursively true for all sub-trees of
that binary tree.
Input: {1, 1, 1, 2, 3, 3, 6, 6, 7}
Output: {1, 2, 3, 6, 7}
Explanation: The given input has only 1,2,3,6, and 7 as unique
elements, hence the output only lists them out.
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
//function that takes an array and its size as arguments
int removeDuplicates(int a[],int n){
int index=0;
for(int i=1;i<n;i++) {
int main()
{
int T;
//taking the number of test cases from user
cin>>T;
//running the loop for all test cases
while(T--)
{
int N;
//taking size input from user
cin>>N;
int a[N];
//taking array input from user
for(int i=0;i<N;i++)
{
cin>>a[i];
}
Solution ob;
//calling the removeDuplicates in the Solution class
int n = ob.removeDuplicates(a,N);
//printing the array after removing duplicates
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
}
Input:
Output: [1, 3, 2, 4, 5, 6, 8, 7]
Explanation: Zigzag Traversal first iterates the given level of the
tree from left to right and then the next level as the right to the
level.
// Tree Node
struct Node {
int data;
Node* left;
Node* right;
};
if(temp->left)
st2.push(temp->left);
if(temp->right)
st2.push(temp->right);
}
//Iterate until the second stack is not empty
while(!st2.empty()){
Node* temp=st2.top();
st2.pop();
result.push_back(temp->data);
if(temp->right)
st1.push(temp->right);
if(temp->left)
st1.push(temp->left);
}
}
return result;
}
Input: 0->1->0->2->1->0->2->1
Output: 0->0->0->1->1->1->2->2
Explanation: All 0’s will come first then 1s and then 2s. This can
be done in O(n) time by counting the occurrences of all three and
rearranging them in the linked list.
Input: n = 4, e = 4 , 0 1, 1 2, 2 3, 3 1
Output: Yes
Explanation: The graph is represented as follows in adjacency list
representation:
0->1
1->2
2->3
3->1
From the above representation, we can see that there exists a cycle:
1→2→3→1
Input: a+b*(c^d)
Output: abcd^*+
int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
public:
// Function to convert an infix expression to a postfix expression.
string infixToPostfix(string s) {
stack<char> st; // For stack operations, we are using C++ built in
stack
string result;
// If an operator is scanned
else {
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
if (c == '^' && st.top() == '^')
break;
else {
result += st.top();
st.pop();
}
}
st.push(c);
}
}
return result;
}
}
j++;
while(!dq.empty()&&arr[dq.back()]<=arr[i])
dq.pop_back();
dq.push_back(i++);
}
ans.push_back(arr[dq.front()]);
return ans;
Input:
First BST
/ \
5 9
Second BST
/ \
3 12
Output: 3 4 5 6 7 9 12
Input:
{{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0},
{0, 1, 0, 0, 1},
{1, 1, 1, 0, 0}}
Output:
{{1, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 0}}
return v;
}
pdt*=nums[right];
while(pdt>=k and left<nums.size()){
pdt/=nums[left];
left++;
}
if(right-left>=0)
ans+=right-left+1;//since on adding a new element new
subarrays formed is r-i+1;
right++;
}
return ans;
}
The three increasing elements of the given arrays are 10, 11, and 12,
which form a three-size subsequence with the highest product.
class Solution{
public:
Node* partition(Node *l, Node *h){
//Your code goes here
Node*temp = h;
Node*tt = l;
Node*first = l;
while(tt != h){
if(tt->data <= temp->data){
swap(first->data, tt->data);
first = first->next;
}
tt = tt -> next;
}
swap(first-> data, h->data);
return first;
}
};
Input: 100
/ \
13 15
/ \ \
14 1 20
/ \
/ \ \
class Solution
{
public:
//Function to connect nodes at the same level.
void connect(Node *p)
{
map<int,vector<Node *> > m;
queue<Node *> q;
queue<int> l;
q.push(p);
l.push(0);
while(!q.empty())
{
Node *temp=q.front();
int level=l.front();
q.pop();
l.pop();
m[level].push_back(temp);
if(temp->left!=NULL)
{
q.push(temp->left);
l.push(level+1);
}
if(temp->right!=NULL)
{
q.push(temp->right);
l.push(level+1);
}
}
for(map<int,vector<Node *> > ::iterator it=m.begin();it!
=m.end();it++)
{
vector<Node *> temp1=it->second;
for(int i=0;i<temp1.size()-1;i++)
{
temp1[i]->nextRight=temp1[i+1];
}
temp1[temp1.size()-1]->nextRight=NULL;
}
}
};
Input: N = 3
1 3 3 21
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
class Solution
{
public:
//function to calculate binomial coefficient C(n,k)
long long int binomialCoefficient(long long int n, long long int k)
{
long long int res = 1;
if (k > n - k)
k = n - k;
return res;
}
// return 2nCn/(n+1)
return C/(n+1);
}
int cap;
node_t head;
unordered_map<int, node_t*> tbl;
class Solution {
public:
The main idea to solve this problem is to traverse the tree in pre
order manner and pass the level information along with it. If the
level is visited for the first time, then we store the information of
the current node and the current level in the hashmap. Basically,
we are getting the left view by noting the first node of every level.
At the end of traversal, we can get the solution by just traversing
the map.
Consider the following tree as example for finding the left view:
Left view of a binary tree in Java:
import java.util.HashMap;
Node(int data) {
this.data = data;
}
}
public class InterviewBit
{
// traverse nodes in pre-order way
public static void leftViewUtil(Node root, int level,
HashMap<Integer, Integer> map)
{
if (root == null) {
return;
}
// traverse the tree and find out the first nodes of each level
leftViewUtil(root, 1, map);
leftView(root);
}
}
Constraints are:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] can only be ‘0’ or ‘1’.
Example:
Input: grid = [
[“1” , “1” , “1” , “0” , “0”],
[“1” , “1” , “0” , “0” , “0”],
[“0” , “0” , “1” , “0” , “1”],
[“0” , “0” , “0” , “1” , “1”]
]
Output: 3
class InterviewBit {
public int numberOfIslands(char[][] grid) {
if(grid==null || grid.length==0||grid[0].length==0)
return 0;
int m = grid.length;
int n = grid[0].length;
int count=0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[i][j]=='1'){
count++;
mergeIslands(grid, i, j);
}
}
}
return count;
}
if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
return;
grid[i][j]='X';
// V - total vertices
// visited - boolean array to keep track of visited nodes
// graph - adjacency list.
// Main Topological Sort Function.
void topologicalSort()
{
Stack<Integer> stack = new Stack<Integer>();
Conclusion
In this post, we covered the most important and frequently asked Data
Structures interview questions. We've also included some pointers and
tricks to help you prepare for the interview. When preparing for the
product-based companies interview, keep in mind that the Data
Structures interview is a critical component of the process. It is critical
that you are well prepared for the interview because it will determine
whether or not you are hired. As a result, it is critical to begin planning
as soon as possible.
Programming: DSA
- https://www.interviewbit.com/courses/programming/
Data Structure MCQ - https://www.interviewbit.com/data-structure-
mcq/
Best Books for Data Structures and Algorithms
- https://www.interviewbit.com/blog/data-structures-and-
algorithms-books/
Best Data Structures and Algorithms Course
- https://www.interviewbit.com/blog/best-courses-for-data-
structures-and-algorithms/
Algorithm Interview Questions
- https://www.interviewbit.com/algorithm-interview-questions/
Master Data Structures and Algorithms With the Scaler Academy
Program - https://www.scaler.com/courses/data-structures-and-
algorithms/
Array
Linked List
Queue
Tree
2.
Graph
AVL Tree
Red-Black Tree
Stack
3.
Array
Stack
Queue
Linked List
4.
Queue
Trees
Linear Arrays
None of the above
5.
B-Tree
Binary Search Tree
AVL Tree
B+- Tree
7.
Using the least significant bit of one of the node's pointers to store
colour information
another array with the colours of each node
Keeping colour data in the node structure
employing both negative and positive numbering
8.
The less frequently the split occurs, if the order of B-tree is large
The split occurs more frequently, if the order of B-tree is large
The more frequently the split occurs, if the order of B-tree is small
The less frequently the split occurs, if the order of B-tree is small
10.
O(n)
O(log(n))
O(nlog(n))
O(n^2)
11.
Arrays
Records
Pointers
Stacks
12.
Weakly connected
Strongly connected
Tightly connected
Linearly connected
13.
BFS
DFS
Level Order
Width first
14.
REAR = REAR + 1
REAR = (REAR + 1) % (QUEUE_SIZE+1)
REAR = (REAR + 1) % (QUEUE_SIZE)
REAR = (REAR - 1) % (QUEUE_SIZE-1)
15.
(log2n) + 1
logn
(logn) + 1
log2n
17.
Which of the following scenario is true for the statement - “Arrays are
best data structures”?
For the size of the structure and the data in the structure are
constantly changing
For relatively permanent collections of data
Both A and B
None of the above
19.
A)
B)
C)
D)
What will be the final elements on the stack if the following sequence of
operations are executed?
* Push(a,s);
* Push(b,s);
* Pop(s);
* Push(c,s);
- where a, b, c are the data elements and s is the stack.
abc
ac
acb
b
21.