0% found this document useful (0 votes)
13 views27 pages

DS Interview Questions: 1. What Is Data Structure?

The document outlines various data structure concepts, including definitions, types, operations, and applications. It explains linear and non-linear data structures, algorithms, memory structures, and specific implementations like linked lists, stacks, and queues. Additionally, it covers the differences between data structures and their use cases in programming and software development.

Uploaded by

Deb Paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views27 pages

DS Interview Questions: 1. What Is Data Structure?

The document outlines various data structure concepts, including definitions, types, operations, and applications. It explains linear and non-linear data structures, algorithms, memory structures, and specific implementations like linked lists, stacks, and queues. Additionally, it covers the differences between data structures and their use cases in programming and software development.

Uploaded by

Deb Paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

DS Interview Questions

1. What is Data Structure?


The data structure is a way that specifies how to organize and manipulate the data. It also defines the
relationship between them. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.

2. Describe the types of Data Structures?


Linear Data Structure: A data structure is called linear if all of its elements are arranged in the sequential
order. In linear data structures, the elements are stored in a non-hierarchical way where each item has the
successors and predecessors except the first and last element.
Non-Linear Data Structure: The Non-linear data structure does not form a sequence i.e. each item or
element is connected with two or more other items in a non-linear arrangement. The data elements are
not arranged in the sequential structure.

3. How linear data structures differ from non-linear data structures?


 If the elements of a data structure result in a sequence or a linear list then it is called a linear data
structure. Whereas, traversal of nodes happens in a non-linear fashion in non-linear data
structures.
 Lists, stacks, and queues are examples of linear data structures whereas graphs and trees are the
examples of non-linear data structures.
4. What are the various operations that can be performed on different Data Structures?
 Insertion : Add a new data item in the given collection of data items.
 Deletion : Delete an existing data item from the given collection of data items.
 Traversal : Access each data item exactly once so that it can be processed.
 Searching : Find out the location of the data item if it exists in the given collection of data items.
 Sorting : Arranging the data items in some order i.e. in ascending or descending order in case of
numerical data and in dictionary order in case of alphanumeric data.

5. List the area of applications of Data Structure.


Data structures form the core foundation of software programming as any efficient algorithm to a given
problem is dependent on how effectively a data is structured.
 Identifiers look ups in compiler implementations are built using hash tables.
 The B-trees data structures are suitable for the databases implementation.
 Some of the most important areas where data structures are used are as follows:
1. AI & ML
2. Compiler design
3. Database design and management
4. Blockchain
5. Operating system development

6. 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.

7. 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.

8. What is the difference between file structure and storage structure?


 File Structure : Representation of data into secondary or auxiliary memory say any device such as
hard disk or pen drives that stores data which remains intact until manually deleted is known as a
file structure representation.
 Storage Structure : In this type, data is stored in the main memory i.e RAM, and is deleted once the
function that uses this data gets completely executed.
The difference is that storage structure has data stored in the memory of the computer system,
whereas file structure has the data stored in the auxiliary memory.

9. List the data structures which are used in RDBMS, Network Data Modal, and Hierarchical Data Model.
o RDBMS uses Array data structure
o Network data model uses Graph
o Hierarchal data model uses Trees

10. Explain the process behind storing a variable in memory.


The required amount of memory is assigned first. Then, it is stored based on the data structure being used.
Using concepts like dynamic allocation ensures high efficiency and that the storage units can be accessed
based on requirements in real time.

41. Do dynamic memory allocations help in managing data?


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.

13. What are dynamic Data Structures?


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 : dynamic array, linked list, stack, queue, and heap.

56) What is the difference between NULL and VOID?


1. Null is actually a value, whereas Void is a data type identifier.
2. A null variable simply indicates an empty value, whereas void is used to identify pointers as having
no initial size.
3. Null means it never existed; Void means it existed but is not in effect

55) List Some Applications of Multilinked Structures?


1. Sparse matrix, 2. Index generation.
16)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.

18) What is a multidimensional array?


The multidimensional array can be defined as the array of arrays in which, the data is stored in tabular
form consists of rows and columns. 2D arrays are created to implement a relational database lookalike
data structure. It provides ease of holding the bulk of data at once which can be passed to any number of
functions wherever required.

19) How are the elements of a 2D array are stored in the memory?
There are two techniques by using which, the elements of a 2D array can be stored in the memory.
o Row-Major Order: In row-major ordering, all the rows of the 2D array are stored into the memory
contiguously. First, the 1st row of the array is stored into the memory completely, then the 2nd row
of the array is stored into the memory completely and so on till the last row.
o Column-Major Order: In column-major ordering, all the columns of the 2D array are stored into the
memory contiguously. first, the 1st column of the array is stored into the memory completely, then
the 2nd row of the array is stored into the memory completely and so on till the last column of the
array.

20) Calculate the address of a random element present in a 2D array, given base address as BA.
Row-Major Order: If array is declared as a[m][n] where m is the number of rows while n is the number of
columns, then address of an element a[i][j] of the array stored in row major order is calculated as,
Address(a[i][j]) = B. A. + (i * n + j) * size
Column-Major Order: If array is declared as a[m][n] where m is the number of rows while n is the number
of columns, then address of an element a[i][j] of the array stored in column major order is calculated as,
Address(a[i][j]) = ((j*m)+i)*Size + BA.

44. Explain the jagged array.


It is an array whose elements themselves are arrays and may be of different dimensions and sizes.

21) Define Linked List Data structure.


It’s a linear Data Structure or a sequence of data objects where elements are not stored in adjacent
memory locations. The elements are linked using pointers to form a chain. Each element is a separate
object, called a node. Each node has two items: a data field and a reference to the next node. The entry
point in a linked list is called the head. Where the list is empty, the head is a null reference and the last
node has a reference to null.
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]

9. What is a doubly-linked list (DLL)? What are its applications.


This is a complex type of a linked list wherein a node has two references - One that connects to the next
node in the sequence, another that connects to the previous node. This structure allows traversal of the
data elements in both directions (left to right and vice versa).
Applications of DLL are:
o A music playlist with next song and previous song navigation options.
o The browser cache with BACK-FORWARD visited pages
o The undo and redo functionality on platforms such as word, paint etc, where you can reverse the
node to get to the previous page.

22) 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.

23) What are the advantages of Linked List over an array?


1. Insertion and Deletion
 Insertion and deletion process is expensive in an array as the room has to be created for the
new elements and existing elements must be shifted.
 But in a linked list, the same operation is an easier process, as we only update the address
present in the next pointer of a node.
2. Dynamic Data Structure
 Linked list is a dynamic data structure that means there is no need to give an initial size at
the time of creation as it can grow and shrink at runtime by allocating and deallocating
memory.
 Whereas, the size of an array is limited as the number of items is statically stored in the
main memory.
3. No wastage of memory
 As the size of a linked list can grow or shrink based on the needs of the program, there is no
memory wasted because it is allocated in runtime.
 In arrays, if we declare an array of size 10 and store only 3 elements in it, then the space for
3 elements is wasted. Hence, chances of memory wastage are more in arrays.

8. Explain the scenarios where you can use linked lists and arrays.
Following are the scenarios where we use linked list over array :
o When we do not know the exact number of elements beforehand.
o When we know that there would be large number of add or remove operations.
o Less number of random-access operations.
o When we want to insert items anywhere in the middle of the list, such as when implementing a
priority queue, linked list is more suitable.
Below are the cases where we use arrays over the linked list :
o When we need to index or randomly access elements more frequently.
o When we know the number of elements in the array beforehand in order to allocate the right
amount of memory.
o When we need speed while iterating over the elements in the sequence.
o When memory is a concern: Due to the nature of arrays and linked list, it is safe to say that filled
arrays use less memory than linked lists. Each element in the array indicates just the data whereas
each linked list node represents the data as well as one or more pointers or references to the other
elements in the linked list.

42. Name the ways to determine whether a linked list has a loop.
 Using hashing
 Using the visited nodes method (with or without modifying the basic linked list data structure)
 Floyd’s cycle-finding algorithm

25. What pointer type should be used to implement the heterogeneous linked list in C language?
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.

6) Which data structure is used to perform recursion?


Stack data structure is used in recursion due to its last in first out nature. Operating system maintains the
stack in order to save the iteration variables at each function call.

10. What is a stack? What are the applications of stack?


Stack is a linear data structure that follows LIFO (Last In First Out) approach for accessing elements. PUSH,
POP, and TOP (or PEEK) are the basic operations of a stack.
Following are some of the applications of a stack:
o Check for balanced parentheses in an expression
o Evaluation of a postfix expression
o Problem of Infix to postfix conversion
o Reverse a string

10) Write the stack overflow condition.


Overflow occurs when top = Maxsize -1

11) What is the difference between PUSH and POP?


PUSH : PUSH specifies that data is being "inserted" into the stack. PUSH takes two arguments, the name of
the stack to add the data to and the value of the entry to be added.
POP : POP specifies data retrieval. It means that data is being deleted from the stack. POP only needs the
name of the stack.

12) Write the steps involved in the insertion and deletion of an element in the stack.
Push:
o Increment the variable top so that it can refer to the next memory allocation
o Copy the item to the at the array index value equal to the top
o Repeat step 1 and 2 until stack overflows

Pop:
o Store the topmost element into another variable
o Decrement the value of the top
o Return the topmost element

25. What are Infix, prefix, Postfix notations?


Infix notation: X + Y – Operators are written in between their operands. This is the usual way we write
expressions.
An expression such as : A * ( B + C ) / D
Postfix notation (or “Reverse Polish notation”): An expression in which operators follow the operands is
known as postfix expression. The main benefit of this form is that there is no need to group sub-
expressions in parentheses or to consider operator precedence. X Y + Operators are written after their
operands.
The infix expression given above is equivalent to : A B C + * D/
Prefix notation (or “Polish notation”): An expression in which operands follow the opertors is known as
prefix expression. + X Y Operators are written before their operands.
The expressions given above are equivalent to : / * A + B C D

15) Which notations are used in Evaluation of Arithmetic Expressions using prefix and postfix forms?
Polish and Reverse Polish notations.

11. What is a queue? What are the applications of queue?


A queue is a linear data structure that follows the FIFO (First In First Out) approach for accessing elements.
DEQUEUE, ENQUE, FRONT and REAR are basic operations that can be performed in Queue.
Some of the applications of queue are:
o CPU Task scheduling
o BFS algorithm to find shortest distance between two nodes in a graph.
o Website request processing
o Used as buffers in applications like MP3 media player, CD player, etc.
o Managing an Input stream

30) What are the drawbacks of array implementation of Queue?


Memory Wastage: The space of the array, which is used to store queue elements, can never be reused to
store the elements of that queue because the elements can only be inserted at front end and the value of
front might be so high so that, all the space before that, can never be filled.
Array Size: There might be situations in which, we may need to extend the queue to insert more elements
if we use an array to implement queue, It will almost be impossible to extend the array size, therefore
deciding the correct array size is always a problem in array implementation of queue.

31) What are the scenarios in which an element can be inserted into the circular queue?
o If (rear + 1)%maxsize = front, the queue is full. In that case, overflow occurs and therefore, insertion
can not be performed in the queue.
o If rear != max - 1, the rear will be incremented to the mod(maxsize) and the new value will be
inserted at the rear end of the queue.
o If front != 0 and rear = max - 1, it means that queue is not full therefore, set the value of rear to 0
and insert the new element there.

32) 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.
21. What is a priority queue?
A priority queue is an abstract data type that is like a normal queue but has priority assigned to elements.
Elements with higher priority are processed before the elements with a lower priority.
In order to implement this, a minimum of two queues are required - one for the data and the other to
store the priority.

14. How to implement a queue using stack?


A queue can be implemented using two stacks. Let q be the queue and stack1 and stack2 be the 2 stacks
for implementing q. We know that stack supports push, pop, peek operations and using these operations,
we need to emulate the operations of queue - enqueue and dequeue. Hence, queue q can be implemented
in two methods (Both the methods use auxiliary space complexity of O(n)):
1. By making enqueue operation costly: Here, the oldest element is always at the top of stack1 which
ensures dequeue operation to occur in O(1) time complexity. To place element at top of stack1,
stack2 is used.
Enqueue: Here time complexity will be O(n)
enqueue(q, data):
While stack1 is not empty:
Push everything from stack1 to stack2.
Push data to stack1
Push everything back to stack1.
Dequeue: Here time complexity will be O(1)
deQueue(q):
If stack1 is empty then error
else
Pop an item from stack1 and return it
2. By making dequeue operation costly : 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 new stack takes O(n) complexity.
Enqueue: Time complexity: O(1)
enqueue(q, data):
Push data to stack1
Dequeue: Time complexity: O(n)
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.

15. 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 : This method ensures that newly entered element is always at
the front of ‘q1’, so that pop operation just dequeues from ‘q1’. ‘q2’ is used as auxillary queue to
put every new element at front of ‘q1’ while ensuring pop happens in O(1) complexity.
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 : In push operation, the element is enqueued to q1. 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.
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.

40. What is a heap data structure?


Heap is a special tree-based non-linear data structure in which the tree is a complete binary tree. A binary
tree is said to be complete if all levels are completely filled except possibly the last level and the last level
has all elements towards as left as possible. Heaps are of two types:
Max-Heap : In a Max-Heap the data element present at the root node must be greatest among all the data
elements present in the tree. This property should be recursively true for all sub-trees of that binary tree.
Min-Heap : 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. This property should be recursively true for all sub-trees
of that binary tree.

24. What are the advantages of the heap over a stack?


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

23. What is a tree data structure?


Tree is a recursive, non-linear data structure consisting of the set of one or more data nodes where one
node is designated as the root and the remaining nodes are called as the children of the root. Tree
organizes data into hierarchical manner.
Some of the applications of trees are:
 Filesystems —files inside folders that are inturn inside other folders.
 Comments on social media — comments, replies to comments, replies to replies etc form a tree
representation.
 Family trees — parents, grandparents, children, and grandchildren etc that represents the family
hierarchy.

28. What are tree traversals?


Tree traversal is a process of visiting all the nodes of a tree. Since 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 :
Inorder Traversal :
Step 1. Traverse the left subtree, i.e., call Inorder(root.left)
Step 2. Visit the root.
Step 3. Traverse the right subtree, i.e., call Inorder(root.right)
Uses: In binary search trees (BST), inorder traversal gives nodes in ascending order.
Preorder Traversal :
Step 1. Visit the root.
Step 2. Traverse the left subtree, i.e., call Preorder(root.left)
Step 3. Traverse the right subtree, i.e., call Preorder(root.right)
Uses: Preorder traversal is commonly used to create a copy of the tree. It is also used to get prefix
expression of an expression tree.
Postorder Traversal :
Step 1. Traverse the left subtree, i.e., call Postorder(root.left)
Step 2. Traverse the right subtree, i.e., call Postorder(root.right)
Step 3. Visit the root.
Uses: Postorder traversal is commonly used to delete the tree. It is also useful to get the postfix expression
of an expression tree.

Inorder Traversal => Left, Root, Right : [4, 2, 5, 1, 3]


Preorder Traversal => Root, Left, Right : [1, 2, 4, 5, 3]
Postorder Traversal => Left, Right, Root : [4, 5, 2, 3, 1]

36) What are Binary trees?


A binary Tree is a special type of generic tree in which, each node can have at most two children. Binary
tree is generally partitioned into three disjoint subsets, i.e. the root of the node, left sub-tree and Right
binary sub-tree.
38) What is the maximum number of nodes in a binary tree of height k?
Maximum nodes : 2k+1-1 where k >= 1

31. Print Left view of any binary trees.


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.

29. What is a Binary Search Tree?


A binary search tree (BST) is a variant of binary tree data structure that stores data in a very efficient
manner such that the values of the nodes in the left sub-tree are less than the value of the root node, and
the values of the nodes on the right of the root node are correspondingly higher than the root.
Also, individually the left and right sub-trees are their own binary search trees at all instances of time.

45. How to check if a given Binary Tree is BST or not?


If inorder traversal of a binary tree is sorted, then the binary tree is BST. The idea is to simply do inorder
traversal and while traversing keep track of previous key value. If current key value is greater, then
continue, else return false.

30. What is an AVL Tree?


AVL(Adelson, Velskii and Landi) trees are height balancing BST. AVL tree checks the height of left and right
sub-trees and assures that the difference is not more than 1. This difference is called Balance Factor.
BalanceFactor = height(left subtree) − height(right subtree)

43) How can AVL Tree be useful in all the operations as compared to Binary search tree?
AVL tree controls the height of the binary search tree by not letting it be skewed. The time taken for all
operations in a binary search tree of height h is O(h). However, it can be extended to O(n) if the BST
becomes skewed (i.e. worst case). By limiting this height to log n, AVL tree imposes an upper bound on
each operation to be O(log n) where n is the number of nodes.
45) What are the differences between B tree and B+ tree?

S B Tree B+ Tree
N

1 Search keys cannot repeatedly be stored. Redundant search keys can be present.

2 Data can be stored in leaf nodes as well as Data can only be stored on the leaf nodes.
internal nodes

3 Searching for some data is a slower process Searching is comparatively faster as data
since data can be found on internal nodes as can only be found on the leaf nodes.
well as on the leaf nodes.

4 Deletion of internal nodes is so complicated Deletion will never be a complexed process


and time-consuming. since element will always be deleted from
the leaf nodes.

5 Leaf nodes cannot be linked together. Leaf nodes are linked together to make the
search operations more efficient.

40) Which data structure suits the most in the tree construction?
Queue data structure

44) State the properties of B Tree.


A B tree of order m contains all the properties of an M way tree. In addition, it contains the following
properties. Every node in a B-Tree contains at most m children. Every node in a B-Tree except the root
node and the leaf node contain at least m/2 children. The root nodes must have at least 2 nodes. All leaf
nodes must be at the same level.

36) What is 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.

46. How do you find the height of a node in a tree?


The height of the node equals the number of edges in the longest path to the leaf from the node, where
the depth of a leaf node is 0.

32. What is a graph data structure?


Graph is a type of non-linear data structure that consists of vertices or nodes connected by edges or links
for storing data. Edges connecting the nodes may be directed or undirected.
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices and E(G)
represents the set of edges which are used to connect these vertices. A graph can be seen as a cyclic tree,
where the vertices (Nodes) maintain any complex relationship among them instead of having parent-child
relations.
Graphs are used in wide varieties of applications. Some of them are as follows:
 Social network graphs to determine the flow of information in social networking websites like
facebook, linkedin etc.
 Neural networks graphs where nodes represent neurons and edge represent the synapses between
them
 Transport grids where stations are the nodes and routes are the edges of the graph.
 Power or water utility graphs where vertices are connection points and edge the wires or pipes
connecting them.
 Shortest distance between two end points algorithms.

48) Differentiate among cycle, path, and circuit?


Path: A Path is the sequence of adjacent vertices connected by the edges with no restrictions.
Cycle: A Cycle can be defined as the closed path where the initial vertex is identical to the end vertex.
Any vertex in the path cannot be visited twice
Circuit: A Circuit can be defined as the closed path where the initial vertex is identical to the end
vertex. Any vertex may be repeated.

34. How do you represent a graph?


We can represent a graph in 2 ways:
1. Adjacency matrix: Used for sequential data representation
2. Adjacency list: Used to represent linked data

35. What is the difference between tree and graph data structure?
1. Tree and graph are differentiated by the fact that a tree structure must be connected and can never
have loops whereas in the graph there are no restrictions.
2. Tree provides insights on relationship between nodes in a hierarchical manner and graph follows a
network model.

8) Explain what is Skip list?


Skip list the method for data structuring, where it allows the algorithm to search, delete and insert
elements in a symbol table or dictionary. In a skip list, each element is represented by a node. The search
function returns the content of the value related to key. The insert operation associates a specified key
with a new value, while the delete function deletes the specified key.

16. What is hashmap in data structure?


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

17. What is the requirement for an object to be used as key or value in HashMap?
The key or value object that gets used in hashmap must implement equals() and hashcode() method. The
hash code is used when inserting the key object into the map and equals method is used when trying to
retrieve a value from the map.

18. How does HashMap handle collisions in Java?


The java.util.HashMap class in Java uses the approach of chaining to handle collisions. In chaining, if the
new values with same key are attempted to be pushed, then these values are stored in a linked list stored
in bucket of the key as a chain along with the existing value.
In the worst case scenario, it can happen that all key might have the same hashcode, which will result in
the hash table turning into a linked list. In this case, searching a value will take O(n) complexity as opposed
to O(1) time due to the nature of the linked list. Hence, care has to be taken while selecting hashing
algorithm.

19. 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 hash map distributes elements
uniformly among the buckets.

22. Can we store a duplicate key in HashMap?


No, duplicate keys cannot be inserted in HashMap. If you try to insert any entry with an existing key, then
the old value would be overridden with the new value. Doing this will not change the size of HashMap. This
is why the keySet() method returns all keys as a SET in Java since it doesn't allow duplicates.

20. Which data structures are used for implementing LRU cache?
LRU cache or Least Recently Used cache allows quick identification of an element that hasn’t been put to
use for the longest time by organizing items in order of use. In order to achieve this, two data structures
are used:
 Queue – This is implemented using a doubly-linked list. The maximum size of the queue is
determined by the cache size, i.e by the total number of available frames. The least recently used
pages will be near the front end of the queue whereas the most recently used pages will be
towards the rear end of the queue.
 Hashmap – Hashmap stores the page number as the key along with the address of the
corresponding queue node as the value.
24) Write the syntax in C to create a node in the singly linked list.
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node));

27) Write the C program to insert a node in circular singly list at the beginning.
#include<stdio.h>
#include<stdlib.h>
void beg_insert(int);
struct node
{
int data;
struct node *next;
};
struct node *head;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
beg_insert(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void beg_insert(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
struct node *temp;
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
ptr -> data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp->next != head)
temp = temp->next;
ptr->next = head;
temp -> next = ptr;
head = ptr;
}
printf("\nNode Inserted\n");
}
}

41) Write the recursive C function to count the number of nodes present in a binary tree.
int count (struct node* t)
{
if(t)
{
int l, r;
l = count(t->left);
r=count(t->right);
return (1+l+r);
}
else
{
return 0;
}
}

42) Write a recursive C function to calculate the height of a binary tree.


int countHeight(struct node* t)
{
int l,r;
if(!t)
return 0;
if((!(t->left)) && (!(t->right)))
return 0;
l=countHeight(t->left);
r=countHeight(t->right);
return (1+((l>r)?l:r));
}

26. Write a recursive function to calculate the height of a binary tree in Java.
Consider that every node of a tree represents a class called Node as given below:
public class Node{
int data;
Node left;
Node right;
}
Then the height of the binary tree can be found as follows:
int heightOfBinaryTree(Node node)
{
if (node == null)
return 0; // If node is null then height is 0 for that node.
else
{
// compute the height of each subtree
int leftHeight = heightOfBinaryTree(node.left);
int rightHeight = heightOfBinaryTree(node.right);
//use the larger among the left and right height and plus 1 (for the root)
return Math.max(leftHeight, rightHeight) + 1;
}
}

27. Write Java code to count number of nodes in a binary tree.


int countNodes(Node root)
{
int count = 1; //Root itself should be counted
if (root ==null)
return 0;
else
{
count += countNodes(root.left);
count += countNodes(root.right);
return count;
}
}

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


void in-order(struct treenode *tree)
{
if(tree != NULL)
{
in-order(tree→ left);
printf("%d",tree→ root);
in-order(tree→ right);
}
}

Inorder traversal in Java:


// Print inorder traversal of given tree.
void printInorderTraversal(Node root)
{
if (root == null)
return;
//first traverse to the left subtree
printInorderTraversal(root.left);

//then print the data of node


System.out.print(root.data + " ");
//then traverse to the right subtree
printInorderTraversal(root.right);
}

Preorder traversal in Java:


// Print preorder traversal of given tree.
void printPreorderTraversal(Node root)
{
if (root == null)
return;
//first print the data of node
System.out.print(root.data + " ");
//then traverse to the left subtree
printPreorderTraversal(root.left);
//then traverse to the right subtree
printPreorderTraversal(root.right);
}

Postorder traversal in Java:


// Print postorder traversal of given tree.
void printPostorderTraversal(Node root)
{
if (root == null)
return;
//first traverse to the left subtree
printPostorderTraversal(root.left);
//then traverse to the right subtree
printPostorderTraversal(root.right);
//then print the data of node
System.out.print(root.data + " ");
}

45. Consider the following tree as example for finding the left view:

Left view of a binary tree in Java:


import java.util.HashMap;
//to store a Binary Tree node
class Node
{
int data;
Node left = null, right = null;
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;
}
// if you are visiting the level for the first time
// insert the current node and level info to the map
if (!map.containsKey(level)) {
map.put(level, root.data);
}
leftViewUtil(root.left, level + 1, map);
leftViewUtil(root.right, level + 1, map);
}
// to print left view of binary tree
public static void leftView(Node root)
{
// create an empty HashMap to store first node of each level
HashMap<Integer, Integer> map = new HashMap<>();
// traverse the tree and find out the first nodes of each level
leftViewUtil(root, 1, map);
// iterate through the HashMap and print the left view
for (int i = 0; i <map.size(); i++) {
System.out.print(map.get(i) + " ");
}
}
public static void main(String[] args)
{
Node root = new Node(4);
root.left = new Node(2);
root.right = new Node(6);
root.left.left = new Node(1);
root.left.left = new Node(3);
root.right.left = new Node(5);
root.right.right = new Node(7);
root.right.left.left = new Node(9);
leftView(root);
}
}

39. Given an m x n 2D grid map of '1’s which represents land and '0’s that represents water, return the
number of islands (surrounded by water and formed by connecting adjacent lands in 2 directions -
vertically or horizontally). Assume that the boundary cases - which is all four edges of the grid are
surrounded by water.
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
Solution:
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;
}
public void mergeIslands(char[][] grid, int i, int j){
int m=grid.length;
int n=grid[0].length;
if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
return;
grid[i][j]='X';
mergeIslands(grid, i-1, j);
mergeIslands(grid, i+1, j);
mergeIslands(grid, i, j-1);
mergeIslands(grid, i, j+1);
}
}
Can doubly-linked be implemented using a single pointer variable in every node?
A doubly linked list can be implemented using a single pointer. See XOR Linked List – A Memory Efficient
Doubly Linked List
Linked List Questions
 Linked List Insertion
 Linked List Deletion
 middle of a given linked list
 Nth node from the end of a Linked List
Tree Traversal Questions
 Inorder
 Preorder and Postoder Traversals
 Level order traversal
 Height of Binary Tree
Convert a DLL to Binary Tree in-place
See In-place conversion of Sorted DLL to Balanced BST
Convert Binary Tree to DLL in-place
See Convert a given Binary Tree to Doubly Linked List | Set 1, Convert a given Binary Tree to Doubly Linked
List | Set 2
Delete a given node in a singly linked list
Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
Reverse a Linked List
Write a function to reverse a linked list
Detect Loop in a Linked List
Write a C function to detect loop in a linked list.
Which data structure is used for dictionary and spell checker?
Data Structure for Dictionary and Spell Checker?

You might also like