Data Structures and Algorithms in Python Educative Quiz Answers

Get Data Structures and Algorithms in Python Educative Quiz Answers

Data structures and algorithms are among the most fundamental concepts of Computer Science. Whether it’s real-world problems you’re trying to solve or the typical coding question asked in an interview, almost every problem requires you to demonstrate a deep understanding of data structures and algorithms.

This course is a detailed review of some of the most common data structures and algorithms that you’ll see in interviews and your everyday work. With implementation details, thorough explanations, and hands-on coding exercises, you’ll quickly gain the confidence you need to solve any problem, no matter the situation.

Enroll on Educative

Exercise 1: Convert Decimal Integer to Binary

Answer:

from stack import Stack

def convert_int_to_bin(dec_num):
    
    if dec_num == 0:
        return 0
    
    s = Stack()

    while dec_num > 0:
        remainder = dec_num % 2
        s.push(remainder)
        dec_num = dec_num // 2

    bin_num = ""
    while not s.is_empty():
        bin_num += str(s.pop())

    return bin_num

Quiz 1: Stacks

Q1. The peek operation of stack removes and returns the top of the stack.

  • True
  • False

Q2. Which of the following is true about stacks?

  • Stacks follow the First-In, First-Out property.
  • New elements are inserted at the bottom of the stack
  • Stacks follow the First-In, Last-Out property
  • Stack is always implemented using linked lists.

Q3. Removing the top element from the stack requires moving out all the elements in the stack.

  • True
  • False

Q4. What is the output of the following code?

myStack = Stack()
myStack.push("A")
myStack.push("B")
myStack.pop()
myStack.push("C")
myStack.push("D")
myStack.pop()
myStack.pop()
print(myStack.peek())
  • A
  • B
  • C
  • D

Q5. What are the basic operations of a stack?

  • Option 1
push()
pop()
  • Option 2
push()
pop()
isEmpty()
peek()
  • Option 3
push()
pop()
isEmpty()
  • Option 4
push()
pop()
isEmpty()
peek()
get_stack()

Exercise 2: Move Tail to Head

Answer:

    def move_tail_to_head(self):
        if self.head and self.head.next:
            last = self.head 
            second_to_last = None
            while last.next:
                second_to_last = last
                last = last.next
            last.next = self.head 
            second_to_last.next = None 
            self.head = last

Exercise 3: Sum Two Linked Lists

Answer:

    def sum_two_lists(self, llist):
        p = self.head  
        q = llist.head

        sum_llist = LinkedList()

        carry = 0
        while p or q:
            if not p:
                i = 0
            else:
                i = p.data
            if not q:
                j = 0 
            else:
                j = q.data
            s = i + j + carry
            if s >= 10:
                carry = 1
                remainder = s % 10
                sum_llist.append(remainder)
            else:
                carry = 0
                sum_llist.append(s)
            if p:
                p = p.next
            if q:
                q = q.next
        return sum_llist

Quiz 2: Singly Linked Lists

Q1. Which of the following is the correct implementation of the Node class?

  • Option 1
class Node:
   def __init__(self, data):
    self.head = data
    self.next = None
  • Option 2
class Node:
   def __init__(self):
    self.head = None
  • Option 3
class Node:
   def __init__(self, data):
    self.data = data
    self.head = None
  • Option 4
class Node:
   def __init__(self, data):
    self.data = data
    self.next = None

Q2. Given that you have access to the head node of a singly linked list containing n elements, what is the time complexity to access an element in a singly linked list?

  • O(1)
  • O(logn)
  • O(n)
  • O(nlogn)

Q3. Elements of a linked list may or may not be stored consecutively in memory?

  • True
  • False

Q4. What will be the output of the following code?

class LinkedList:
  def __init__(self):
    self.head = None

  def append(self, data):
    new_node = Node(data)
    last_node = self.head
    while last_node.next:
      last_node = last_node.next
    last_node.next = new_node
  
  llist = LinkedList()
  llist.append("A")
  llist.append("B")
  llist.print_list()  
  • A B
  • A
  • No output
  • Error

Q5. For a singly linked list containing n elements, what is the time complexity to delete the head node given that you have access to the head node?

  • O(1)
  • O(logn)
  • O(n)
  • O(n2)

Exercise 4: Is Circular Linked List

Answer:

    def is_circular_linked_list(self, input_list):
        if input_list.head:
            cur = input_list.head
            while cur.next:
                cur = cur.next
                if cur.next == input_list.head:
                    return True
            return False
        else:
            return False

Quiz 3: Circular Linked Lists

Q1. Given that you have access to the head node of a circular linked list containing n elements, what is the time complexity to search for an element?

  • O(1)
  • O(logn)
  • O(n)
  • O(n2)

Q2. A linked list is a circular linked list when the tail node points to itself.

  • True
  • False

Q3. Given that you have access to the head node, the time complexity of removing the head node in a circular linked list containing n elements is O(1).

  • True
  • False

Q4. What is the output of the following code?

cllist = CircularLinkedList()
cllist.append("A")
cllist.prepend("B")
cllist.prepend("C")
cllist.append("D")

cllist.remove("A")
cllist.remove("C")
print(cllist.head.data)
  • A
  • B
  • C
  • D

Q5. What is the time complexity of the following method if we run it on a circular linked list containing n elements?

def print_list(self):
  cur = self.head 

  while cur:
      print(cur.data)
      cur = cur.next
      if cur == self.head:
          break
  • O(1)
  • O(n/2)
  • O(2n)
  • O(n)

Exercise 5: Remove Duplicates

Answer:

  def remove_duplicates(self):
    cur = self.head 
    seen = dict()
    while cur:
      if cur.data not in seen:
          seen[cur.data] = 1
          cur = cur.next
      else:
          nxt = cur.next
          self.delete_node(cur)
          cur = nxt

  def delete_node(self, node):
      cur = self.head
      while cur:
        if cur == node and cur == self.head:
          # Case 1:
          if not cur.next:
            cur = None 
            self.head = None
            return

          # Case 2:
          else:
            nxt = cur.next
            cur.next = None 
            nxt.prev = None
            cur = None
            self.head = nxt
            return 

        elif cur == node:
          # Case 3:
          if cur.next:
            nxt = cur.next 
            prev = cur.prev
            prev.next = nxt
            nxt.prev = prev
            cur.next = None 
            cur.prev = None
            cur = None
            return

          # Case 4:
          else:
            prev = cur.prev 
            prev.next = None 
            cur.prev = None 
            cur = None 
            return 
        cur = cur.next

Exercise 6: Pairs with Sums

Answer:

  def pairs_with_sum(self, sum_val):  
    pairs = list()
    p = self.head 
    q = None 
    while p:
      q = p.next
      while q:
        if (p.data + q.data) == sum_val:
          pairs.append("(" + str(p.data) + "," + str(q.data) + ")")
        q = q.next
      p = p.next
    return pairs

Quiz 4: Doubly Linked Lists

Q1. The code below is an implementation of the Node class for which of the following linked lists?

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None
  • Singly Linked Lists
  • Circular Linked Lists
  • Doubly Linked Lists
  • None of the above

Q2. What is the output of the following code?

class DoublyLinkedList:
    ...
  def delete(self, key):
          cur = self.head
          while cur:
              if cur.data == key:
                  if cur.next:
                      nxt = cur.next 
                      prev = cur.prev
                      prev.next = nxt
                      nxt.prev = prev
                      cur.next = None 
                      cur.prev = None
                      cur = None
                      return
                  else:
                      prev = cur.prev 
                      prev.next = None 
                      cur.prev = None 
                      cur = None 
                      return 
              cur = cur.next

dllist = DoublyLinkedList()
dllist.append(1)
dllist.append(2)
dllist.append(3)

dllist.delete(3)
dllist.delete(1)

dllist.print_list()          
  • 1 2 3
  • 2
  • No output
  • Error

Q3. Doubly Linked List has more efficient methods to insert and delete elements than singly linked lists.

  • True
  • False

Q4. The prev attribute of a Node object is supposed to point to which of the following?

  • The next attribute of the previous node in the doubly linked list
  • The data attribute of the previous node in the doubly linked list
  • The previous node in the doubly linked list
  • The head node of the doubly linked list

Q5. What is the output of the following code?

class DoublyLinkedList:
     ...
    def print_list(self):
        cur = self.head
        while cur.next:
            cur = cur.next
        
        while cur:
            print(cur.data)
            cur = cur.prev


dllist = DoublyLinkedList()
dllist.prepend(0)
dllist.append(1)
dllist.append(2)
dllist.append(3)
dllist.append(4)
dllist.prepend(5)

dllist.print_list()
  • 5 0 1 2 3 4
  • 4 3 2 1 0 5
  • No output
  • Error

Exercise 7: Buy and Sell Stock

Answer:

def buy_and_sell_stock_once(prices):
  max_profit = 0.0
  min_price = float('inf')
  for price in prices:
    min_price = min(min_price, price)
    compare_profit = price - min_price
    max_profit = max(max_profit, compare_profit)
  return max_profit

Exercise 8: Calculating the Size of a Tree

Answer:

    def size_(self, node):
      if node is None:
          return 0
      return 1 + self.size_(node.left) + self.size_(node.right)

Quiz 5: Binary Trees

Q1. What is the total number of edges from a particular node to its deepest descendant in a tree?

  • The depth of that particular node
  • The height of that particular node
  • The depth of the tree
  • The height of the tree

Q2. Fill in the blank: A binary tree in which every node has either 0 or 2 children is called __________.

  • a binary search tree
  • a complete binary tree
  • a full binary tree
  • a balanced binary tree

Q3. The Level Order Traversal is a type of depth-first traversal.

  • True
  • False

Q4. What is the output of the following code?

tree = BinaryTree(12)
tree.root.left = Node(32)
tree.root.right = Node(37)
tree.root.left.left = Node(24)
tree.root.left.right = Node(5)
tree.root.right.left = Node(100)
tree.root.right.right = Node(75)

print(tree.print_tree("postorder"))
  • 5-12-24-32-37-75-100
  • 12-32-24-5-37-100-75-
  • 24-5-100-75-32-37-12-
  • 24-5-32-100-75-37-12-

Q5. What is the time complexity of the depth-first traversals of a tree containing n nodes?

  • O(n)
  • O(logn)
  • O(nlogn)
  • O(n2)

Exercise 9: Checking the BST property

Answer:

    def is_bst_satisfied(self):
        def helper(node, lower=float('-inf'), upper=float('inf')):
            if not node:
                return True
            
            val = node.data
            if val <= lower or val >= upper:
                return False

            if not helper(node.right, val, upper):
                return False
            if not helper(node.left, lower, val):
                return False
            return True

        return helper(self.root)

Quiz 6: Binary Search Trees

Q1. The worst-case time complexity of insert, search and delete operations in a binary search tree is as follows:

  • O(1)
  • O(logn)
  • O(n)
  • O(nlogn)

Q2. BST property:

The value of the left child of any node in a binary search tree will be less than whatever value we have in that node, and the value of the right child of a node will be equal to the value in that node.

  • True
  • False

Q3. Is the following tree a valid binary search tree?

  • True
  • False

Q4. What is the average time complexity of the following code?

def search(self, find_val):
  return self.search_helper(self.root, find_val)

def search_helper(self, current, find_val):
  if current:
    if current.data == find_val:
        return True
    elif current.data < find_val:
        return self.search_helper(current.right, find_val)
    else:
        return self.search_helper(current.left, find_val)
  • O(n/2)
  • O(logn)
  • O(n)
  • O(nlogn)

Q5. Which of the following is a valid implementation of the Node class for a binary search tree?

  • Option 1
class Node:
    def __init__(self, val): 
        self.val = val
        self.Child = None
        self.parent = None
  • Option 2
class Node:
    def __init__(self, val): 
        self.val = val
        self.parent = None
  • Option 3
class Node:
    def __init__(self, val): 
        self.val = val
        self.leftChild = None 
        self.rightChild = None
  • Option 4
class Node:
    def __init__(self, val):
        self.val = val
        self.Child = None

Exercise 10: Integer Square Root

Answer:

def integer_square_root(k):
    low = 0
    high = k

    while low <= high:
        mid = (low + high) // 2
        mid_squared = mid * mid

        if mid_squared <= k:
            low = mid + 1
        else:
            high = mid - 1
    return low - 1

Exercise 11: Cyclically Shifted Array

Answer:

def find(A):
  low = 0
  high = len(A) - 1

  while low < high:
    mid = (low + high) // 2
    
    if A[mid] > A[high]:
        low = mid + 1
    elif A[mid] <= A[high]:
        high = mid

  return low

Quiz 7: Binary Search

Q1. Binary search is only applicable in case of sorted lists.

  • True
  • False

Q2. What is the worst-case time complexity of the recursive approach of a binary search?

  • O(logn)
  • O(n)
  • O(nlogn)
  • O(2n)

Q3. What is the worst-case time complexity of the iterative approach of a binary search?

  • O(logn)
  • O(n)
  • O(nlogn)
  • O(2n)

Q4. Binary search works by comparing the target element with the values on the first and the last index of a list.

  • True
  • False

Q5. What is the output of the following code?

def binary_search_recursive(data, target, low, high):
    if low > high:
        return False
    else:
        mid = (low + high) // 2
        if target < data[mid]:
            return binary_search_recursive(data, target, low, mid-1)
        else:
            return binary_search_recursive(data, target, mid+1, high)
data = [2,4,5,7,8,9]
target = 2
print(binary_search_recursive(data, target, 0, 5))
  • 2
  • True
  • False
  • No output

Exercise 12: Product of Two Positive Integers

Answer:

def recursive_multiply(x, y):
    if x < y:
        return recursive_multiply(y, x)
    if y == 0:
        return 0
    return x + recursive_multiply(x, y-1)

Quiz 8: Recursion

Q1. Recursive implementations are always less space-consuming then iterative implementations.

  • True
  • False

Q2. Fill in the blank for the following recursive function which calculates the power of a base raised to an exponent:

def pow(base,exp):
    if exp == 0: 
        return 1
    else:
        return ___________
  • Option 1
base * exp
  • Option 2
base * (exp -1)* pow(base,exp)
  • Option 3
base * pow(base, exp - 1)
  • Option 4
exp * pow(base, exp - 1)

Q3. What is the output of the following code?

def fibonacci(n):
    if n==1:
        return 0
    elif n==2:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2) 
print(fibonacci(7)) 
  • No output
  • 7
  • 0
  • 8

Q4. Only recursively defined functions can be implemented recursively.

  • True
  • False

Exercise 13: Is Unique

Answer:

def is_unique(input_str):
    return len(set(input_str)) == len(input_str)

Exercise 14: String to Integer

Answer:

def str_to_int(input_str):
    output_int = 0

    if input_str[0] == '-':
        start_idx = 1
        is_negative = True
    else:
        start_idx = 0
        is_negative = False

    for i in range(start_idx, len(input_str)):
        place = 10**(len(input_str) - (i+1))
        digit = ord(input_str[i]) - ord('0')
        output_int += place * digit

    if is_negative:
        return -1 * output_int
    else:
        return output_int
Conclusion:

I hope this Data Structures and Algorithms in Python Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.