0% found this document useful (0 votes)
46 views

Basic Data Structure Interview Questions For Freshers

Uploaded by

aarti
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Basic Data Structure Interview Questions For Freshers

Uploaded by

aarti
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

Basic Data Structure Interview Questions for Freshers

1. What are Data Structures?

A data structure is a mechanical or logical way that data is organized within a program. The
organization of data is what determines how a program performs. There are many types of data
structures, each with its own uses. When designing code, we need to pay particular attention to the
way data is structured. If data isn't stored efficiently or correctly structured, then the overall
performance of the code will be reduced.

2. Why Create Data Structures?

Data structures serve a number of important functions in a program. They ensure that each line of
code performs its function correctly and efficiently, they help the programmer identify and fix
problems with his/her code, and they help to create a clear and organized code base.

3. What are some applications of Data structures?

Following are some real-time applications of data structures:

 Decision Making
 Genetics
 Image Processing
 Blockchain
 Numerical and Statistical Analysis
 Compiler Design
 Database Design and many more

Describe the types of Data Structures?

 Linear Data Structure: A data structure that includes data elements arranged
sequentially or linearly, where each element is connected to its previous and next nearest
elements, is referred to as a linear data structure. Arrays and linked lists are two examples of
linear data structures.
 Non-Linear Data Structure: Non-linear data structures are data structures in which
data elements are not arranged linearly or sequentially. We cannot walk through all elements in
one pass in a non-linear data structure, as in a linear data structure. Trees and graphs are two
examples of non-linear data structures.

Can you explain the difference between file structure and storage structure?

The difference is that the storage structure has data stored in the memory of the computer system( i.e.,
RAM) is deleted once the function that uses this data gets completely executed, whereas the file
structure has the data stored in the auxiliary memory(i.e., Hard disk, pen drive) which remains intact
until manually deleted ..

1
What is an asymptotic analysis of an algorithm?

Asymptotic analysis of an algorithm defines the run-time performance as per its mathematical
boundations. Asymptotic analysis helps us articulate the best case(Omega Notation, Ω), average
case(Theta Notation, θ), and worst case(Big Oh Notation, Ο) performance of an algorithm.

What is hashmap in data structure?

Hashmap is a data structure that uses an implementation of a hash table data structure which
allows access to data in constant time (O(1)) complexity if you have the key.

Differentiate between hash code and equals 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.

What is the time complexity of basic operations get() and put() in HashMap class?

The time complexity is O(1) assuming that the hash function used in the hash map distributes
elements uniformly among the buckets.

What are some key operations performed on the Deque data structure?

Following are the key operations available deque:

 insertFront(): This adds an element to the front of the Deque.


 insertLast(): This adds an element to the rear of the Deque.
 deleteFront(): This deletes an element from the front of the Deque.
 deleteLast():This deletes an element from the front of the Deque.
 getFront(): This gets an element from the front of the Deque.
 getRear(): This gets an element from the rear of the Deque.
 isEmpty(): This checks whether Deque is empty or not.
 isFull(): This checks whether Deque is full or not

What is the difference between an array and a linked list?

Array and Linked list are two ways of organizing the data in memory. The below table lists the various
differences between the array and linked lists:

Array Linked List


A Linked list is a set of objects known as a node,
An array is a sequence of elements of a similar data
where it internally consists of two parts, i.e., data
type.
and address.

2
Linked lists support random access. Only supports
It can be accessed irregularly using the array index.
sequential access.
New elements can be stored anywhere, and a
Array elements store in contiguous locations in
reference is created for the new element using
memory.
pointers.
In arrays, memory allocation is done during In linked lists, memory allocation is done during
compile time. runtime.
Array size must be defined at the time of Linked list size grows when new elements are
declaration/initialization. inserted or deleted.

What operations can be performed on a stack?

Mainly the following operations are performed on a stack:

 Push operation: To add an item to the stack. If the stack is complete, then it is in an overflow
condition.
 Pop operation: It is used to remove an item from the stack. If it's an empty stack, then it is in
underflow condition.

 isEmpty operation: If the stack is empty returns true, else false.

 Peek or Top operation: This returns the top element of the stack.

Explain about Linked List Data Structure.

A linked list is a series of data structures connected via links. In simple words, it's a sequence of links
that contain items. After the array, the linked list is the second most used data structure. The essential
terms to understand the linked list are:

Link - In a linked list, each link stores data called an element.

Next - In a linked list, each link is connected to the following link called next.

LinkedList - It contains the connection link to the first link called first.

List a few queue data structure applications.

As the name suggests, the queue is used whenever you need to manage a group of objects in the order
FIFO. A few of the queue data structure applications are listed below:

 Serving requests on a single shared resource, like CPU task scheduling, printer, etc.
 Handling interruptions in real-time systems.

 Buffers in apps like CD player and MP3 media players

 In maintaining a playlist in media players, like adding or removing songs.

What is the difference between stack and heap?

Both stack and heap are used for memory needs. The stack is primarily used to save the method
execution order and local variables, and always follow the LIFO order.

Whereas heap is used for dynamic allocation and deallocation of memory blocks. It stores objects in
Java. Memory allocated to the heap lives until one of the following events occurs:
3
 Memory free
 Program terminated

The size of heap memory is more when using recursion when compared with the stack, as it quickly
fill-ups stack memory.

Name a few graph data structure applications.

Applications of graph data structures in real-time are:


 Social graphs
 Path optimization algorithms
 Recommendation engines

 Scientific computations

Which data structures do you use in DFS and BFS algorithms?

 In the DFS algorithm, you use the Stack data structure.


 In the BFS algorithm, you use the Queue data structure.

How to find the height of a node in a tree?

You can find the height of a binary tree using a recursive Depth-First Search (DFS) algorithm, as
shown below:

 Base case: If there is no node, return 0.


 Else: If there are 1 or 2 children, return the peak of the height of the left and right subtrees,
plus 1 to account for the current node.

Explain what is a linked list?

A linked list is nothing but a sequence of nodes. With this sequence, each node is connected to the
following node. It forms a chain of data storage.

Write the postfix form of the expression: (A + B) * (C - D)

AB+CD-*

What is an array?

Arrays are defined as the collection of similar types of data items stored at contiguous memory locations. It
is the simplest data structure in which each data element can be randomly accessed by using its index
number.

Are linked lists considered linear or non-linear data structures?

A linked list is considered both linear and non-linear data structure depending upon the situation.

o On the basis of data storage, it is considered as a non-linear data


structure.
o On the basis of the access strategy, it is considered as a linear data-
structure.

Write the syntax in C to create a node in the singly linked list.


4
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node));

If you are using C language to implement the heterogeneous linked list, what pointer type should be
used?
The heterogeneous linked list contains different data types, so it is not possible to use ordinary pointers for
this. For this purpose, you have to use a generic pointer type like void pointer because the void pointer is
capable of storing a pointer to any type.

What is a dequeue?
Dequeue (also known as double-ended queue) can be defined as an ordered set of elements in which the
insertion and deletion can be performed at both the ends, i.e. front and rear.

What is the minimum number of queues that can be used to implement a priority queue?

Two queues are needed. One queue is used to store the data elements, and another is used for storing
priorities.

Write the C code to perform in-order traversal on a binary tree.


1. void in-order(struct treenode *tree)
2. {
3. if(tree != NULL)
4. {
5. in-order(tree→ left);
6. printf("%d",tree→ root);
7. in-order(tree→ right);
8. }
9. }

List Some Applications of Multilinked Structures?


o Sparse matrix,
o Index generation.

What is the difference between NULL and VOID?


o Null is actually a value, whereas Void is a data type identifier.
o A null variable simply indicates an empty value, whereas void is used to identify pointers as
having no initial size.

Differentiate Single, Double and Circulated Linked list.


5
A linked list is a linear data structure (like arrays) where each element is a separate object. Each element
(that is node) of a list is comprised of two items – the data and a reference to the next node. Types of
Linked List :
1. Singly Linked List : In this type of linked list, every node stores address or reference of the next
node in the list and the last node has next address or reference as NULL. For example 1->2->3->4-
>NULL
2. Doubly Linked List : Here, here are two references associated with each node, One of the
reference points to the next node and one to the previous node. Eg. NULL<-1<->2<->3->NULL
3. Circular Linked List : Circular linked list is a linked list where all nodes are connected to form a
circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or a
doubly circular linked list. Eg. 1->2->3->1 [The next pointer of the last node is pointing to the
first]

What is a stack data structure? What are the applications of stack?

A stack is a data structure that is used to represent the state of an application at a particular point in time.
The stack consists of a series of items that are added to the top of the stack and then removed from the top.
It is a linear data structure that follows a particular order in which operations are performed. LIFO (Last In
First Out) or FILO (First In Last Out) are two possible orders. A stack consists of a sequence of items. The
element that's added last will come out first, a real-life example might be a stack of clothes on top of each
other. When we remove the cloth that was previously on top, we can say that the cloth that was added last
comes out first.

Following are some applications for stack data structure:

 It acts as temporary storage during recursive operations


 Redo and Undo operations in doc editors
 Reversing a string
 Parenthesis matching
 Postfix to Infix Expressions
 Function calls order

What is a queue data structure? What are the applications of queue?

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.

Following are some applications of queue data structure:


 Breadth-first search algorithm in graphs
 Operating system: job scheduling operations, Disk scheduling, CPU scheduling etc.
 Call management in call centres

Differentiate between stack and queue data structure.

Stack Queue

Stack is a linear data structure where data is Queue is a linear data structure where data is ended at the
6
Stack Queue

added and removed from the top. rear end and removed from the front.

Stack is based on LIFO(Last In First Out)


Queue is based on FIFO(First In First Out) principle
principle

Insertion operation in Stack is known as push. Insertion operation in Queue is known as eneque.

Delete operation in Stack is known as pop. Delete operation in Queue is known as dequeue.

Only one pointer is available for both addition Two pointers are available for addition and deletion:
and deletion: top() front() and rear()

Used in solving recursion problems Used in solving sequential processing problems

7
What is a multidimensional array?
A multidimensional array is a multidimensional array with more than one dimension. It is an array of
arrays or an array with numerous layers. The 2D array, or two-dimensional array, is the most basic
multidimensional array. As you'll see in the code, it's technically an array of arrays. A 2D array is also
referred to as a matrix or a table with rows and columns. Declaring a multidimensional array is the same as
saying a one-dimensional array. We need to notify C that we have two dimensions for a two-dimensional
array.

How are the elements of a 2D array stored in the memory?


1. Row-Major Order: -In row-major ordering, all of the rows of a 2D array are stored in memory in
a contiguous manner.
First, the first row of the array is entirely stored in memory, followed by the second row of the
array, and so on until the final row.
1. Column-Major Order: In column-major ordering, all of the columns of a 2D array are stored in
memory in the same order. The first column of the array is entirely saved in memory, followed by
the second row of the array, and so on until the last column of the array is wholly recorded in
memory.

What is a doubly-linked list? Give some examples.


It is a complex type (double-ended LL) of a linked list in which a node has two links, one that connects to
the next node in the sequence and another that connects to the previous node. This allows traversal across
the data elements in both directions.
Examples include:
 A music playlist with next and previous navigation buttons
 The browser cache with BACK-FORWARD visited pages
 The undo and redo functionality on a browser, where you can reverse the node to get to the
previous page
How do you reference all of the elements in a one-dimension array?

Using an indexed loop, we may access all of the elements in a one-dimensional array. The counter counts
down from 0 to the maximum array size, n, minus one. The loop counter is used as the array subscript to
refer to all items of the one-dimensional array in succession.

What are dynamic Data Structures? Name a few.


They are collections of data in memory that expand and contract to grow or shrink in size as a program
runs. This enables the programmer to control exactly how much memory is to be utilized.
Examples are the dynamic array, linked list, stack, queue, and heap.

What is an algorithm?
An algorithm is a step by step method of solving a problem or manipulating data. It defines a set of
instructions to be executed in a certain order to get the desired output.

8
Why do we need to do an algorithm analysis?
A problem can be solved in more than one way using several solution algorithms. Algorithm
analysis provides an estimation of the required resources of an algorithm to solve a specific computational
problem. The amount of time and space resources required to execute is also determined.

The time complexity of an algorithm quantifies the amount of time taken for an algorithm to run as a
function of the length of the input.
The space complexity quantifies the amount of space or memory taken by an algorithm, to run as a
function of the length of the input.

What are the advantages of the heap over a stack?

Generally, both heap and stack are part of memory and used in Java for different needs:
 Heap is more flexible than the stack because memory space can be dynamically allocated and de-
allocated as needed
 Heap memory is used to store objects in Java, whereas stack memory is used to store local
variables and function call
 Objects created in the heap are visible to all threads, whereas variables stored in stacks are only
visible to the owner as private memory
 When using recursion, the size of heap memory is more whereas it quickly fill-ups stack
memory

What is the difference between a PUSH and a POP?


The acronyms stand for Pushing and Popping operations performed on a stack.
These are ways data is stored and retrieved.
 PUSH is used to add an item to a stack, while POP is used to remove an item.
 PUSH takes two arguments, the name of the stack to add the data to and the value of the entry to
be added. POP only needs the name of the stack.
 When the stack is filled and another PUSH command is issued, you get a stack overflow
error, which means that the stack can no longer accommodate the last PUSH.
In POP, a stack underflow error occurs when you’re trying to POP an already empty stack.

What is the merge sort? How does it work?

Merge sort is a divide-and-conquer algorithm for sorting the data. It works by merging and sorting adjacent
data to create bigger sorted lists, which are then merged recursively to form even bigger sorted lists until
you have one single sorted list.

Define the graph Data Structure?


It is a type of non-linear data structure that consists of vertices or nodes connected by edges or arcs to
enable storage or retrieval of data. Edges may be directed or undirected

Do dynamic memory allocations help in managing data? How?


Dynamic memory allocation stores simple structured data types at runtime. It has the ability to combine
separately allocated structured blocks to form composite structures that expand and contract as needed,
thus helping manage data of data blocks of arbitrary size, in arbitrary order.

9
List the types of trees?
 The General Tree
A tree is referred to as a generic tree if its hierarchy is not constrained. In the General Tree, each node can
have an endless number of offspring, and all other trees are subsets of the tree.
 The Binary Tree
The binary tree is a type of tree in which each parent has at least two offspring. The children are referred to
as the left and right youngsters. This tree is more popular than most others. When specific limitations and
features are given to a Binary tree, various trees such as AVL tree, BST (Binary Search Tree), RBT tree,
and so on are also utilized.
 Tree of Binary Search
Binary Search Tree (BST) is a binary tree extension that includes numerous optional constraints. In BST, a
node's left child value should be less than or equal to the parent value, while the correct child value should
always be higher than or equal to the parent's value.
 The AVL Tree
The AVL tree is a self-balancing binary search tree. The term AVL is given in honor of the inventors
Adelson-Velshi and Landis. This was the first tree to achieve dynamic equilibrium. Each node in the AVL
tree is assigned a balancing factor based on whether the tree is balanced or not. The node kids have a
maximum height of one AVL vine.
 Red and Black Tree
Red-black trees are another type of auto-balancing tree. The red-black term is derived from the qualities of
the red-black tree, which has either red or black painted on each node. It helps to keep the forest in balance.
Even though this tree is not perfectly balanced, the searching process takes just O (log n) time.
 The N-ary Tree
In this sort of tree with a node, N is the maximum number of children. A binary tree is a two-year tree
since each binary tree node has no more than two offspring. A full N-ary tree is one in which the children
of each node are either 0 or N.

10
How do you implement stack using queues?

 A stack can be implemented using two queues. We know that a queue supports enqueue
and dequeue operations. Using these operations, we need to develop push, pop operations.
 Let stack be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Then, stack ‘s’ can be
implemented in two ways:

1. By making push operation costly:

1. This method ensures that the newly entered element is always at the front of ‘q1’ so that
pop operation just dequeues from ‘q1’.
2. ‘q2’ is used as auxillary queue to put every new element in front of ‘q1’ while ensuring
pop happens in O(1) complexity.

Pseudocode:

o Push element to stack s: Here push takes O(n) time complexity.

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 element from stack s: Takes O(1) time complexity.

pop(s):
dequeue from q1 and return it.

2. By making pop operation costly:

1. In push operation, the element is enqueued to q1.


2. In pop operation, all the elements from q1 except the last remaining element, are pushed to
q2 if it is empty. That last element remaining of q1 is dequeued and returned.

Pseudocode:

o Push element to stack s: Here push takes O(1) time complexity.

push(s,data):
Enqueue data to q1
 Pop element from stack s: Takes O(n) time complexity.

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.

11
Mirror characters of a string

Given a string and a number N, we need to mirror the characters from N-th position up to
the length of the string in the alphabetical order. In mirror operation, we change ‘a’ to
‘z’, ‘b’ to ‘y’, and so on.

Input : N = 3
paradox
Output : paizwlc
We mirror characters from position 3 to end.

Input : N = 6
pneumonia
Output : pnefnlmrz

Missing number in array

Given an array of size N-1 such that it only contains distinct integers in the range
of 1 to N. Find the missing element.
Example 1:
Input:
N=5
A[] = {1,2,3,5}
Output: 4

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending
order.
Example 1:
Input:
N=5
arr[]= {0 2 1 2 0}

Output:
00122
Explanation:
0s 1s and 2s are segregated into ascending order.
Example 2:
Input:
N=3
arr[] = {0 1 0}
Output:
001
Explanation:
0s 1s and 2s are segregated into ascending order.
12
13

You might also like