0% found this document useful (0 votes)
163 views17 pages

DSA ORAL Question Bank

File structure refers to data stored on secondary storage like a hard disk that remains until deleted, while storage structure refers to data stored in RAM that is deleted after the function using it finishes. Linear data structures like lists and queues have sequential elements while non-linear structures like trees and graphs have non-sequential traversal. Common examples of linear structures are arrays and linked lists, while trees and graphs are examples of non-linear structures. Hashmaps allow O(1) access if you have the key but cannot store duplicate keys.
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)
163 views17 pages

DSA ORAL Question Bank

File structure refers to data stored on secondary storage like a hard disk that remains until deleted, while storage structure refers to data stored in RAM that is deleted after the function using it finishes. Linear data structures like lists and queues have sequential elements while non-linear structures like trees and graphs have non-sequential traversal. Common examples of linear structures are arrays and linked lists, while trees and graphs are examples of non-linear structures. Hashmaps allow O(1) access if you have the key but cannot store duplicate keys.
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/ 17

1.

Can you explain 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.
2. Can you tell 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.

Types
 There are two types of data structures:
 Linear data structure: If the elements of a data structure result in a
sequence or a linear list then it is called a linear data structure. Example: Arrays, Linked
List, Stacks, Queues etc.
 Non-linear data structure: If the elements of data structure results in a way
that traversal of nodes is not done in a sequential manner, then it is a non linear data
structure. Example: Trees, Graphs etc.

Applications
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. Artificial intelligence
2. Compiler design
3. Machine learning
4. Database design and management
5. Blockchain
6. Numerical and Statistical analysis
7. Operating system development
8. Image & Speech Processing
9. Cryptography
1. 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.
2. 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 hierarchial manner.
 The most commonly used tree data structure is a binary tree and its
variants.
 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.

3. 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.
4. 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.
5. 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.
6. 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.

7. What are Binary trees?

 A binary Tree is a special type of tree where each node can have at most
two children. Binary tree is generally partitioned into three disjoint subsets, i.e. the root of
the tree, left sub-tree and right sub-tree.

8. What is the maximum number of nodes in a binary tree of height


k?

 The maximum nodes are : 2k+1-1 where k >= 1


9. 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;
 }
 }

10. 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 += count(root.left);
count += count(root.right);
return count;
}
}

11. 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:
 Algorithm:
 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)
 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);
 }
 Uses: In binary search trees (BST), inorder traversal gives
nodes in ascending order.
 Preorder Traversal:
 Algorithm:
 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)
 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);
 }
 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:
 Algorithm:
 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.
 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 + " ");

 }
 Uses:
 Postorder traversal is commonly used to delete the
tree.
 It is also useful to get the postfix expression of an
expression tree.
 Consider the following tree as an example, then:
 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]
12. 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.

30. What is an AVL Tree?


 AVL 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 and is calculates as. BalanceFactor =
height(left subtree) − height(right subtree)

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.
 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);
 }
 }

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.

33. What are the applications of graph data structure?

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.
34. How do you represent a graph?

We can represent a graph in 2 ways:

 Adjacency matrix: Used for sequential data representation


 Adjacency list: Used to represent linked data
35. What is the difference between tree and graph data structure?

 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.
 Tree provides insights on relationship between nodes in a
hierarchical manner and graph follows a network model.
36. What is the difference between the Breadth First Search (BFS) and
Depth First Search (DFS)?

 BFS and DFS both are the traversing methods for a graph. Graph
traversal is nothing but the process of visiting all the nodes of the graph.
 The main difference between BFS and DFS is that BFS traverses
level by level whereas DFS follows first a path from the starting to the end node, then
another path from the start to end, and so on until all nodes are visited.
 Furthermore, BFS uses queue data structure for storing the nodes
whereas DFS uses the stack for traversal of the nodes for implementation.
 DFS yields deeper solutions that are not optimal, but it works well
when the solution is dense whereas the solutions of BFS are optimal.
 You can learn more about BFS here: Breadth First Search and
DFS here: Depth First Search.
37. How do you know when to use DFS over BFS?

 The usage of DFS heavily depends on the structure of the search


tree/graph and the number and location of solutions needed. Following are the best cases
where we can use DFS:
 If it is known that the solution is not far from the root
of the tree, a breadth first search (BFS) might be better.
 If the tree is very deep and solutions are rare, depth
first search (DFS) might take an extremely long time, but BFS could be faster.
 If the tree is very wide, a BFS might need too much
memory, so it might be completely impractical. We go for DFS in such cases.
 If solutions are frequent but located deep in the tree
we opt for DFS.
38. What is topological sorting in a graph?

 Topological sorting is a linear ordering of vertices such that for


every directed edge ij, vertex i comes before j in the ordering.
 Topological sorting is only possible for Directed Acyclic Graph
(DAG).
 Applications:
 jobs scheduling from the given dependencies among
jobs.
 ordering of formula cell evaluation in spreadsheets
 ordering of compilation tasks to be performed in
make files,
 data serialization
 resolving symbol dependencies in linkers.
2. Topological Sort Code in Java:
// 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>();

// Mark all the vertices as not visited


boolean visited[] = new boolean[V];
for (int j = 0; j < V; j++){
visited[j] = false;
}
// Call the util function starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack);

// Print contents of stack -> result of topological sort


while (stack.empty() == false)
System.out.print(stack.pop() + " ");
}

// A helper function used by topologicalSort


void topologicalSortUtil(int v, boolean visited[],
Stack<Integer> stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i;

// Recur for all the vertices adjacent to the current vertex


Iterator<Integer> it = graph.get(v).iterator();
while (it.hasNext()) {
i = it.next();
if (!visited[i])
topologicalSortUtil(i, visited, stack);
}

// Push current vertex to stack that saves result


stack.push(new Integer(v));
}

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:
3. m == grid.length
4. n == grid[i].length
5. 1 <= m, n <= 300
6. 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
7. Solution:
8. class InterviewBit {
9. public int numberOfIslands(char[][] grid) {
10. if(grid==null || grid.length==0||grid[0].length==0)
11. return 0;
12.
13. int m = grid.length;
14. int n = grid[0].length;
15.
16. int count=0;
17. for(int i=0; i<m; i++){
18. for(int j=0; j<n; j++){
19. if(grid[i][j]=='1'){
20. count++;
21. mergeIslands(grid, i, j);
22. }
23. }
24. }
25.
26. return count;
27. }
28.
29. public void mergeIslands(char[][] grid, int i, int j){
30. int m=grid.length;
31. int n=grid[0].length;
32.
33. if(i<0||i>=m||j<0||j>=n||grid[i][j]!='1')
34. return;
35.
36. grid[i][j]='X';
37.
38. mergeIslands(grid, i-1, j);
39. mergeIslands(grid, i+1, j);
40. mergeIslands(grid, i, j-1);
41. mergeIslands(grid, i, j+1);
42. }
43. }
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:

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

You might also like