Django Training and Certification (7 Blogs) Become a Certified Professional

Data Structure Interview Questions and Answers in 2024

Published on Jan 18,2024 229 Views

Maria is a passionate tech enthusiast trying to break down complex concepts... Maria is a passionate tech enthusiast trying to break down complex concepts into easy-to-understand stories.

Data structures are a way of organizing and storing data in a computer’s memory to facilitate efficient processing and retrieval of information. They provide a way to organize and structure data to perform operations on the stored information effectively. Many algorithms are based on the efficient use of data structures. Data structure-related questions are an integral part of technical interviews because they assess a candidate’s problem-solving skills, critical thinking, coding proficiency, and understanding of core computer science concepts. Being able to navigate data structure interview questions effectively can significantly contribute to success in technical interviews.

Bad programmers worry about the code. Good programmers worry about data structures and their relationships.‘ — Linus Torvalds.

Now, let’s explore the Data Structure Interview Questions in three sections- 

Data Structure Interview Questions for Freshers

1. What is a Data Structure? What are the characteristics of data structures?

A data structure is a way of organizing, storing, and managing data to facilitate efficient data access and modification. It defines a set of operations that can be applied to the data, as well as the relationships between the elements. The choice of a particular data structure depends on the nature of the data and the operations that need to be performed.

Characteristics of data structures

  • Organization: Data structures organize and structure data for efficient retrieval, insertion, deletion, and manipulation of elements.
  • Access Methods: Data structures define methods for accessing and manipulating the stored data. These methods may include searching for specific elements, sorting, and traversing the data.
  • Efficiency: Different data structures are designed to optimize specific types of operations. The choice of a data structure depends on the efficiency requirements of the algorithms.
  • Memory Management: Data structures often involve memory management, determining how data is stored in computer memory and how memory is allocated and deallocated.

2. What are the two types of data structures? 

The two important types of data structures are linear and non-linear data structures.

  1. Linear Data Structures: Except for the first and last elements, linear data structures arrange elements in a sequential order, with each element having a distinct predecessor and successor. The elements form a linear sequence. Examples of linear data structures include linked lists, stacks, arrays, and queues.
  2. Non-linear Data Structures: In non-linear data structures, elements are not arranged in a sequential or linear order. Instead, elements can have relationships with multiple predecessors and successors, forming more complex structures. Common examples of non-linear data structures include: Trees, Graphs, Heaps, and Hash Tables.

3. Explain some common Data Structures.

  • Arrays: An array is a collection of fixed-size elements, each identified by an index.
  • Linked Lists: In linked lists, elements are stored in nodes. Each node points to the next node in a sequence, resulting in a linear chain.
  • Stacks: A stack is a collection of elements with two primary operations: push and pop. Here, elements are added and removed from one end.
  • Queues: A queue is a collection of elements with two primary operations, enqueue and dequeue, which add elements at one end (rear) and remove them from the other end (front).
  • Trees: Trees are hierarchical structures with a root node and branches leading to leaf nodes. Trees can be classified into various types, such as binary trees, binary search trees, etc.
  • Graphs: A graph is a collection of vertices or nodes connected by edges. Graphs can be directed or undirected, and they can contain weighted edges. They are used for representing relationships between entities.
  • Heaps: Heaps are specialized tree-based structures. Heaps are commonly used in priority queues and heap sort algorithms.
  • Hash Tables: Hash Tables store data in key-value pairs. A hash function maps keys to indices in an array.

4. Explain how an array differs from a linked list.

  • An array is a data structure that contains a sequential collection of elements with the same data type. Each element in the array is identified by an index that indicates its position in the sequence. At the same time, a linked list is a data structure made up of nodes, each of which contains data and a reference to the next node in the sequence. The last node typically points to null, indicating the end of the list.
  • Elements in an array are stored in contiguous memory locations, allowing direct access to any element using its index. Meanwhile, linked lists do not require contiguous memory locations. Each node can be located anywhere in memory, and they are linked together by pointers, allowing for dynamic memory allocation.
  • Arrays have a fixed size, which means the number of elements is known at the time of declaration. Linked lists can easily grow and shrink in size by adding or removing nodes, making them more flexible in terms of size changes compared to arrays.

5. Define a linked list and its advantages over arrays.

A linked list is a linear data structure and consists of nodes. Each node points to the next node in a sequence, resulting in a linear chain.

Advantages of Linked Lists Over Arrays:

  • One of the significant advantages of linked lists is their dynamic size. Unlike arrays, linked lists can add or remove nodes, making them more flexible in handling data.
  • Linked lists do not require pre-allocation of space for a fixed number of elements, as is the case with arrays. This dynamic memory allocation makes linked lists suitable for situations where the exact size of the data structure is unknown or subject to change.
  • Linked lists are particularly efficient for insertions and deletions at any position within the list. Inserting or deleting elements in between a linked list involves updating pointers.
  • Linked lists do not suffer from the memory wastage that can occur in arrays due to pre-allocation. Memory is allocated on demand for each node in a linked list, minimizing unused space.

6. Describe the basic operations of a stack and a queue.

  1. StackA stack is a data structure that follows the Last In, First Out (LIFO) principle. The basic operations of a stack include:
  • Push – Adds an element to the top of the Stack.
  • Pop – Removes an element from the top of the Stack.
  • Peek – Returns the topmost element from the Stack.
  • isEmpty – Checks if the Stack is empty.
      1. Queue : A queue is another data structure that follows the First In, First Out (FIFO) approach. The basic operations of a queue include:
      • Enqueue – Adds an element to the rear end of the queue.
      • Dequeue – Removes the element from the front of the queue.
      • Front – Returns the element at the front of the queue.
      • isEmpty – Checks if the queue is empty.

      7. What is a Queue, and how is it different from a Stack?

      A queue is a data structure that follows the First In, First Out (FIFO) principle. In a queue, elements are added at the rear (enqueue) and removed from the front (dequeue). Queues are often used in scenarios where the order of processing is important, such as in task scheduling, printing, or managing requests in a network.

      On the other hand, a stack is a data structure that follows the Last In, Last Out (LIFO) approach. In a stack, elements are added and removed from the same end, typically called the “top.” The last element pushed onto the Stack is the first to be popped off. Stacks are commonly used in situations where the order of processing is based on the order of arrival, such as in function calls, expression evaluation, or undo mechanisms.

      8. What is a stack data structure? What are the applications of Stack?

      A stack is a data structure that follows the Last In, First Out (LIFO) principle, i.e., the last element added to the Stack is the first one to be removed. 


      • Function Calls and Recursion : Stacks play a crucial role in managing function calls and recursion in programming languages.
      • Expression Evaluation : Stacks are commonly used for the evaluation of expressions, especially in the context of arithmetic expressions. The stack data structure facilitates the processing of operands and operators, ensuring that the expression is evaluated according to the order of operations. 
      • Backtracking Algorithms : Stacks are commonly used in backtracking algorithms to keep track of the current state and facilitate the process of exploration and backtracking. Backtracking algorithms often use recursion to explore different branches of the solution space. In this case, the call stack itself acts as the stack data structure.
      • Memory Management : Stacks play a critical role in memory management, particularly in the context of managing function calls and local variables. It provides a simple and efficient way to allocate and deallocate memory in a structured manner, contributing to the overall memory management strategy in programming languages and runtime environments.

      9. What is a binary tree data structure? Explain the properties of a binary tree.

      A binary tree is a hierarchical tree data structure in which each node can have no more than two children, known as the left and right children. Edges connect nodes in a binary tree, and there is a unique starting node called the root. The node without any children is called a leaf. Operations such as searching, insertion, and deletion can be performed efficiently in binary trees, especially when the tree is balanced. 

      Here are the key properties of a binary tree:

      • RootA binary tree’s root is the node at the very top. It serves as the starting point for navigating the tree.
      • NodesEach element in a binary tree is called a node. Nodes may contain data and references to their left and right children.
      • EdgesThe connections between nodes are called edges. In a binary tree, each node has at most two edges leading to its children.
      • ParentA node in a binary tree is considered a parent if it has one or more children.
      • ChildrenThe nodes directly below a parent are referred to as its children.
      • Leaf NodesLeaf nodes are nodes with no children. They are the terminal nodes at the bottom of the tree.
      • Internal NodesInternal nodes are nodes that have at least one child. These nodes are not leaves.
      • DepthThe depth of a node is the distance from the root to that node. The root has a depth of 0.

      10. Define a graph and explain the differences between directed and undirected graphs.

      A graph is a computational representation of a set of objects, known as vertices or nodes, connected by edges. Graphs are used to model relationships between entities. The two main components of a graph are:

      • Vertices (Nodes): These are the entities represented in the graph. Each vertex can have additional information associated with it, known as attributes.
      • Edges: These are the connections between vertices. Edges represent relationships or interactions between the entities.

      11. What are the differences between Directed and Undirected Graphs?

      • Directed Graph/Digraph : In a directed graph, edges have a direction, i.e., they have an initial vertex and a terminal vertex. They are ordered.
      • Undirected Graph : In an undirected graph, edges do not have a direction. The connections between vertices are symmetric, and the vertices are unordered.

      Now, let’s go through some common Data Structure interview questions for Experienced Professionals.

      Data Structure Interview Questions for Experienced

      1. What is a Deque?

      A deque, or “double-ended queue,” is a data structure that allows the insertion and deletion of elements from both the front and back. This makes it versatile, as elements can be efficiently added or removed from either end.

      The operations on a deque can be summarized as follows:

      • EnqueueFront: Add an element to the front.
      • EnqueueRear: Add an element to the rear.
      • DequeueFront: Remove an element from the front.
      • DequeueRear: Remove an element from the rear.

      Deques are useful in situations where you need efficient insertion and deletion at both ends of the data structure. They can be employed in algorithms that require maintaining a sliding window of elements, palindrome checking, and other scenarios where elements need to be accessed from both ends.

      2. What is BST? What are its applications?

      A Binary Search Tree is a binary tree data structure where each node has at most two children, and for each node:

      • All nodes in its left subtree have keys smaller than the nodes’.
      • All nodes in its right subtree have keys greater than the nodes’.
      • Both the left and right subtrees are also binary search trees.

      This ordering property ensures that a binary search can be efficiently performed on the tree. 

      Key operations on a binary search tree:

      • Search: The search operation in a Binary Search Tree (BST) involves finding a specific key within the tree. Given a key, the search operation navigates the tree from the root, comparing the key with the current node’s key at each step. If the key matches the current node’s key, the search is successful, and the corresponding value is returned. If the key is smaller, the search continues in the left subtree; if it’s larger, the search continues in the right subtree. If the key is not found after reaching a node, the search operation returns a null indicating that the key is not present.
      • Insertion: The insertion operation starts with a search for the key in the tree. If the key is not found (i.e., the search reaches a leaf node), a new node is created with the given key and value. The new node is then inserted at the appropriate position in the tree while maintaining the BST property. If the key already exists in the tree, the associated value is updated.
      • Deletion: Deleting a node involves three cases:
        1. If the node to be deleted is a leaf (has no children), it can be removed directly.
        2. If the node has one child, the node is replaced by its child.
        3. If the node has two children, it is replaced by its in-order successor (or predecessor), and the in-order successor’s original position is adjusted.
        • Traversal: Traversal in a Binary Search Tree (BST) involves visiting all the nodes of the tree in a specific order. The three common types of binary tree traversal are in-order, pre-order, and post-order. Each traversal method defines a different order in which the nodes are visited. 

        Applications of Binary Search Trees

        • Tables and Dictionaries: Binary Search Trees (BSTs) are widely used to implement tables and dictionaries, providing an efficient way to associate keys with values and allowing for quick retrieval, insertion, and deletion operations.
        • Database Indexing: Binary search trees are used in databases to index and efficiently search for records.
        • File System: File systems often use BSTs to maintain directory structures and quickly locate files.
        • Network Routing Tables: In networking, BSTs can be employed to store routing information efficiently.

        3. What are the ways to traverse a tree?

        The three primary methods to traverse a tree are in-order, pre-order, and post-order traversal. 

        • In-order traversal is a method of traversing a binary tree in which each node is visited in a specific order. The order of visiting nodes in an in-order traversal is left, node, right. This traversal produces the elements of a binary search tree (BST) in ascending order. In the context of a binary tree, “left” refers to the left subtree, “node” refers to the current node, and “right” refers to the right subtree.
        • Pre-order traversal is a method of traversing a binary tree in a specific order: Node – Left – Right. In this traversal, each node is visited before its left and right subtrees. The process starts from the root node, and for each node, the node itself is visited first, followed by the traversal of its left subtree and then its right subtree.
        • Post-order traversal is a method of traversing a binary tree in a specific order: Left – Right – Node. In this traversal, each node’s left and right subtrees are visited before the node itself. The process starts from the root node, and for each node, the left subtree is traversed first, followed by the traversal of the right subtree, and finally, the current node is visited.

        4. Explain different types of queues

          There are mainly four types of queues. They are

          • Linear Queue : In a linear queue, elements are stored linearly or sequentially. The first element is added at one end (rear/enqueue), and elements are removed from the other end (front/dequeue). This is the most basic form of a queue.
          • Circular Queue : A circular queue is an extension of a linear queue where the rear end is connected to the front end, forming a circular structure. This allows for efficient utilization of space and avoids the need to shift elements when the rear reaches the end of the queue. The circular queue is often implemented using an array or a linked list.
          • Priority Queue : In a priority queue, elements are assigned priority values. Elements with higher priority are dequeued before elements with lower priority. Priority queues are used in scenarios where the priority of elements determines the order of processing.
          • Double-Ended Queue (Deque) : A deque allows the insertion and deletion of elements from both ends (front and rear). It can be used as a queue, Stack, or a combination of both. Deques are more versatile than linear queues.

          5. What are the representations of a graph data structure? What are the applications for graphs?

          There are two main representations of graphs: the adjacency matrix and the adjacency list.

          1. An adjacency matrix is a 2D array (matrix) where each cell at position (a, b) represents whether there is an edge between vertex a and vertex b. If there is an edge, the cell contains a 1; otherwise, it contains a 0.
          2. An adjacency list is a collection of lists or arrays where each list represents the neighbors of a vertex. For each vertex v, the list contains all vertices adjacent to v.


          Graphs are versatile data structures with a wide range of applications across various domains. Here are some common applications of graph data structures:

          • Social Networks : Graphs model relationships between individuals in social networks. Nodes represent people, and edges represent connections or friendships. Algorithms on graphs can be used to analyze social network structures, find communities, and suggest connections.
          • Routing and Networks : Graphs model the connections between routers or devices in computer networks. Algorithms like Dijkstra’s or Bellman-Ford can find the shortest path between two nodes. Graphs are also used to model and analyze transportation networks, such as roads and railways.
          • Recommendation Systems : Graphs can represent user-item interactions. Recommendation algorithms analyze the graph to suggest items based on the preferences of similar users.
          • Artificial Intelligence : Graphs are used in knowledge representation, with nodes as concepts and edges as relationships. Graph-based algorithms contribute to machine learning and pattern recognition tasks.

          Learn More: Data Structure Learning Roadmap

          6. What is the difference between BFS and DFS?

          Breadth First Search (BFS) and Depth First Search (DFS) are two fundamental algorithms used to traverse and explore graphs or tree structures.

          Visits nodes level by level, starting from the source node. It explores all the neighbors of a node before moving on to the next level.Visits nodes branch by branch. Goes as deep as possible, exploring each branch before backtracking.
          BFS uses a queue data structure. The first-in, first-out (FIFO) property ensures that nodes are processed in the order they are discovered.DFS uses a stack data structure. The last-in, first-out (LIFO) property ensures that nodes are explored deeply before backtracking.
          Requires more memory compared to DFS because all the nodes at the current level need to be stored in the queue.
          DFS requires less memory compared to BFS as it stores the nodes along the current branch.
          BFS is used for shortest path finding, Web crawling, indexing, and peer-to-peer networks.DFS is used for topological sorting of graphs, Finding connected components, and Solving puzzles.

          7. What are the different types of array data structures?

          Arrays are data structures that store elements of the same type in contiguous memory locations. Here are some common types of array data structures:

          • A one-dimensional array is a simple array that stores elements in a single line or row. Elements are accessed using a single index.


                     [3 1 7 9]

          • A two-dimensional array is an array of arrays forming a matrix or table structure. Elements are accessed using two indices (row and column).


                      [[1 3 4 5]

                      [2 4 5 6]]

          • A multi-dimensional array is an array with more than two dimensions. Here, Elements are accessed using multiple indices.






          8. What are the different types of Linked List data structures?

          Linked lists are linear data structures where elements are stored in nodes, and each node points to the next node in the sequence. Here are some common types of linked lists:

          • Singly Linked List: Each node in a singly linked list contains data as well as a reference to the node following it in the sequence. The last node points to null, indicating the end of the list. Here, Traversal is only possible in one direction.

                     0 -> 1 -> 2 -> 3 -> null

          • Doubly Linked List: In a doubly linked list, each node contains data and references to both the next and the previous nodes in the sequence. Here, Traversal is in both forward and backward directions.

                      null <- 0 <-> 1 <-> 2 <-> 3 -> null

          • Circular Linked List: In a circular linked list, the last node points back to the first, forming a loop. This can be implemented using singly or doubly linked nodes.

                      1 -> 2 -> 3 -> 1

          • Doubly Circular Linked List: A Doubly Circular Linked List is a type of linked list in which each node contains data and two pointers. Similar to a doubly linked list, a doubly circular linked list has pointers to both the next and the previous nodes. However, in a circular linked list, the last node points back to the first node, creating a loop. In a doubly circular linked list, this Loop is formed in both directions.

                      1 <-> 2 <-> 3 <-> 4 <-> 1


                      In the example above, the arrows indicate the direction of the pointers. The last node points back to the first node, forming a circular structure in both directions.

          9. What are infix and postfix expressions?

          • Infix Expression – An infix expression refers to a standard mathematical expression in which operators are placed between operands. In an infix expression, the position of an operator in relation to its operands determines the order of operations, following the rules of precedence and associativity. In infix expressions, parentheses are often used to indicate the order of operations explicitly. The order of operations is as follows:
          1. Parentheses
          2. Exponents
          3. Multiplication and Division (from left to right)
          4. Addition and Subtraction (from left to right)


                  a + b * (c – d) / e

          • Postfix Expression –  In data structures, a postfix expression is a way of representing mathematical expressions in which operators follow their operands. Postfix notation eliminates the need for parentheses to indicate operation order, as operator position determines operation sequence. In a postfix expression, operators are placed after their corresponding operands.


                      a b c d – * e /

          Related Learning: Data Structures in C

          10. Explain the concept of hashing and hash functions.

          Hashing is the process of using a hash function to convert arbitrary-sized data to fixed-size values (hash codes). A hash function is a mathematical function that takes an input and returns a fixed-size string of characters, which is typically a hash code. The resulting hash code is often used as an index to locate a data record in a hash table quickly. The output appears random and unique for different inputs, and even a small change in the input should produce a significantly different hash value. Hashing is commonly employed in various applications, such as hash tables, digital signatures, data integrity checks, and cryptographic applications. A hash table is a data structure that uses hash functions to map keys to indexes in an array. Each index in the array corresponds to a “bucket” where the associated value is stored. Hash tables provide fast average-case time complexity for basic operations like insertion, deletion, and lookup.

          Now, let’s move ahead with some common coding data structure interview questions.

          Data Structure Coding Interview Questions

          1. Given an array of integers, write a function to find the sum of all elements in Python.

          #Function to find the sum of elements

          def sum_func(array1):

              return sum(array1)

          array1 = [1, 2, 3, 4, 5]

          result = sum_func(array1)

          print(f”The sum of elements in the array is: {result}”)


          The sum of elements in the array is: 15

          In this example, the function sum_func takes a list of integers as its parameter and uses the built-in sum_func function to calculate the sum of all elements in the array.

          Related Learning: Data Structures in Python

          2. Program to print the duplicate elements of an array.

          #Initializing the array   

          array = [1, 2, 3, 5, 9, 4, 5, 7, 6, 8, 0, 3, 0];   

          print(“Duplicate elements in the array include: “); 

          #Traversing through the elements using for Loop

          for i in range(0, len(array)):  

              for j in range(i+1, len(array)):  

                  if(array[i] == array[j]):  



             Duplicate elements in the array include: 




          3. Write a program to determine if two strings are anagrams

          string1 = “Heart”;  

          string2 = “Earth”;   

          #Checking for the length of strings  

          if(len(string1)!= len(string2)):  

              print (“The strings are not Anagram”);  


              #Using the lower() function to change the case of the string to lowercase

              string1 = string1.lower();  

              string2 = string2.lower();  

              #Sorting the strings  

              string1 = ”. join(sorted(string1));  

              string2 = ”. join(sorted(string2));  


              if (string1 == string2):  

                  print (“The strings are Anagrams”);   


                  print (“The strings are not Anagrams”);  


          The strings are Anagrams

          4. Write a Program to count the number of vowels in a given string.

          string = “Edureka”

          # Function to count vowel

          def vowels_count(string):

              temp = 0

              #All vowels 

              vowel = set(“aeiouAEIOU”)

              #For Loop to iterate through the string

              for element in string:

                  if element in vowel:

                      temp = temp + 1

              print(“Total number of vowels in the string:”, temp)

          #Testing the Function 



               Total number of vowels in the string: 4

          5. Implement a stack using arrays.

          class Stack:

              def __init__(self):

                  self.items = []

              def is_empty(self):

                  return len(self.items) == 0

              def push(self, item):


              def pop(self):

                  if not self.is_empty():

                      return self.items.pop()


                      raise IndexError(“pop from an empty stack”)

              def peek(self):

                  if not self.is_empty():

                      return self.items[-1]


                      raise IndexError(“peek from an empty stack”)

              def size(self):

                  return len(self.items)

          #Calling the function

          stack1 = Stack()




          #Printing results

          print(“Stack:”, stack1.items)

          print(“Pop:”, stack1.pop())

          print(“Peek:”, stack1.peek())

          print(“Size:”, stack1.size())

          The above example shows the implementation of basic stack operations like push, pop, and peek, checking if the stack is empty and getting the size of the stack. 


            Stack: [1, 2, 3]

            Pop: 3

            Peek: 2

            Size: 2

          6. Write a program to calculate the height of a binary tree.

          class Node:

              def __init__(self, value):

                  self.value = value

                  self.left = None

                  self.right = None

          def tree_height(root):

              if root is None:

                  return 0


                  left_height = tree_height(root.left)

                  right_height = tree_height(root.right)

                  # Return the maximum height of the left and right subtrees, plus 1 for the current level.

                  return max(left_height, right_height) + 1

          #Calling the function

          root = Node(1)

          root.left = Node(2)

          root.right = Node(3)

          root.left.left = Node(4)

          root.left.right = Node(5)

          tree_height = tree_height(root)

          print(“Height of the binary tree:”, tree_height)


          Height of the binary tree: 3

          7. Implement a queue using an array.

          class queue:

              # __init__ function

              def __init__(self, capacity):

                  self.front = self.size = 0

                  self.rear = capacity -1

                  self.Q = [None]*capacity

                  self.capacity = capacity

              # Checking if Queue is full

              def isfull(self):

                  return self.size == self.capacity

              # Checking if Queue is empty

              def isempty(self):

                  return self.size == 0

              # Function to add an element to the queue. 

              def enqueue(self, item):

                  if self.isfull():



                  self.rear = (self.rear + 1) % (self.capacity)

                  self.Q[self.rear] = item

                  self.size = self.size + 1

                  print(“% s enqueued to queue” % str(item))

              # Function to remove an element from the queue. 

              def dequeue(self):

                  if self.isempty():



                  print(“% s dequeued from queue” % str(self.Q[self.front]))

                  self.front = (self.front + 1) % (self.capacity)

                  self.size = self.size -1

              # Function to get front of queue

              def queuefront(self):

                  if self.isempty():

                      print(“Queue is empty”)

                  print(“Front item is”, self.Q[self.front])

              # Function to get rear of the queue

              def queuerear(self):

                  if self.isempty():

                      print(“Queue is empty”)

                  print(“Rear item is”, self.Q[self.rear])

          # Adding elements to the queue

          if __name__ == ‘__main__’:

              queue = queue(4)









                1 enqueued to queue

                2 enqueued to queue

                3 enqueued to queue

                4 enqueued to queue

                1 dequeued from queue

                Front item is 2

                Rear item is 4

          In this example, the queue class represents a queue implemented using a circular array. The enqueue method adds an item to the rear end of the queue, the dequeue method removes and returns the item from the front end of the queue, and the peek method returns the item at the front without removing it. The queue keeps track of its front and rear indices to manage the circular nature of the array.

          8. Write a Python program to reverse a linked list.

          class node: 


              def __init__(self, data): 

         = data 

                  self.next_node = None

          class linked_list: 

              # Initialize head 

              def __init__(self): 

                  self.head_node = None

              # Function to reverse the linked list 

              def reverse_ll(self): 

                  previous_node = None

                  current_node = self.head_node

                  while(current_node is not None): 

                      next_node = current_node.next_node

                      current_node.next_node = previous_node

                      previous_node = current_node 

                      current_node = next_node

                  self.head_node = previous_node

              # Function to push a node 

              def push_node(self, new_data): 

                  new_node = node(new_data) 

                  new_node.next_node = self.head_node 

                  self.head_node = new_node 

              # Printing the LinkedList 

              def print_ll(self): 

                  count = self.head_node


                      print (,end=” “) 

                      count = count.next_node

          # Testing the functions 

          ll = linked_list() 






          print (“Linked List:”) 



          print (“Reversed Linked List:”) 



             Linked List:

             3 8 1 4 2 

             Reversed Linked List

             2 4 1 8 3 

          In the above example, the reverse_ll function takes the head node of the linked list as an input and reverses the links between nodes.

          9. Write a Python Program to count the number of nodes in a complete Binary Tree.

          class node:

              def __init__(self, data):

                  self.left_node = None

                  self.right_node = None

         = data

          # Function to get the total number of nodes in a complete binary tree

          def totalnodes(root_node):

              if(root_node == None):

                  return 0 

              # Find the left height and right height

              left_height = totalnodes(root_node.left_node)

              right_height = totalnodes(root_node.right_node)

              return 1 + left_height + right_height

          # Function to create a new node

          def newNode(data):

              Node = node(data)

              return Node

          # Testing the function

          root_node = newNode(1)

          root_node.left_node = newNode(2)

          root_node.right_node = newNode(3)

          root_node.left_node.left_node = newNode(4)

          root_node.left_node.right_node = newNode(5)

          root_node.right_node.left_node = newNode(6)

          print(“The total number of nodes in the tree is:”,totalnodes(root_node))


            The total number of nodes in the tree is: 6

          10. Write a Python Program to find the length of the linked list:

          class node:

              def __init__(self, data):

         = data  

                  self.next_node = None  

          class Linked_List:

              # Initializing head node

              def __init__(self):

                  self.head_node = None

              # Function to push a node to the Linked List

              def push(self, new_data):

                  new_node = node(new_data)

                  new_node.next_node = self.head_node

                  self.head_node = new_node

              # Function to count the number of nodes in the Linked List

              def nodeCount(self):

                  count = self.head_node # Initialise count

                  nodecount = 0 # Initialise nodecount

                  while (count):

                      nodecount += 1

                      count = count.next_node

                  return nodecount

          #Testing the function

          if __name__ == ‘__main__’:

              ll = Linked_List()







              print(“The total count of nodes in the linked list is :”, ll.nodeCount())


          The total count of nodes in the linked list is: 6

          This brings us to the end of the ‘Data Structure Interview Questions’ blog. This blog covers the most common data structure interview questions through three sections- Interview Questions for freshers, Interview Questions for Experienced, and coding questions. I hope you are clear with all the three sections. Make sure to go through this article before going for the next interview. All the best!

          Have a query for us? Kindly let us know in the comments section, and we’ll get in touch with you.

          Check out Edureka’s Python Developer Masters Program, crafted by industry experts through extensive research, facilitating expertise in Python and its libraries. This program will help you gain proficiency in Data Science, Machine Learning, Deep Learning, and Natural Language Processing through hands-on projects. This program offers a transformative opportunity to upskill, reshape your career, and access new opportunities. Enroll now to embark on your journey to success!


          Join the discussion

          Browse Categories

          REGISTER NOW
          webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

          Subscribe to our Newsletter, and get personalized recommendations.

          image not found!
          image not found!

          Data Structure Interview Questions and Answers in 2024