Combine and Ans With Explaination
Combine and Ans With Explaination
Explanations
This document consolidates questions, answers, and detailed explanations from the four
provided technical tests covering Object-Oriented Programming, Stacks & Queues, Linked
Lists, Trees & Graphs, and Searching & Sorting.
Test 1: Object-Oriented Programming (OOP)
Q.1) What is an object in OOP?
● Answer: [C] An instance of a class
● Explanation: In Object-Oriented Programming, a class serves as a blueprint or
template that defines the properties (attributes) and behaviors (methods) common to
all objects of a certain kind. An object is a concrete entity created from a class; it's an
instance of that class, residing in memory and possessing the characteristics defined by
the class.
Q.2) What is encapsulation in OOP?
● Answer: [A] Protecting properties of class
● Explanation: Encapsulation is one of the fundamental principles of OOP. It refers to the
bundling of data (attributes) and the methods that operate on that data within a single
unit, known as a class. A key aspect of encapsulation is data hiding, which means
restricting direct access to some of an object's components (usually its attributes) from
outside the class. This protection helps prevent accidental or unauthorized modification
of data and promotes a clear interface for interacting with objects.
Q.3) What is inheritance in OOP?
● Answer: [B] Deriving a class from another class
● Explanation: Inheritance is a mechanism that allows a new class (called a subclass,
derived class, or child class) to acquire the properties and methods of an existing class
(called a superclass, base class, or parent class). This promotes code reusability and
establishes an "is-a" relationship between classes (e.g., a Dog is an Animal).
Q.4) What is polymorphism in OOP?
● Answer: [B] Having multiple forms
● Explanation: Polymorphism, meaning "many forms," allows objects of different classes
to be treated as objects of a common superclass and respond to the same method call
in their own specific ways. This is typically achieved through method overriding (where
a subclass provides its own implementation of a method inherited from a superclass)
and interfaces.
Q.5) What is the purpose of the __init__ method in Python?
● Answer: [B] Initializes an object
● Explanation: In Python, __init__ is a special method, known as a constructor. It is
automatically called when an object of a class is created. Its primary purpose is to
initialize the newly created object's attributes (instance variables) with specific values,
setting up its initial state.
Q.6) Which keyword is used to create an object in Python?
● Answer: [D] No keyword is needed
● Explanation: Unlike some other languages (e.g., Java or C++ which use the new
keyword), Python does not require a special keyword to create an object. You create an
instance of a class by calling the class name followed by parentheses, like a function
call (e.g., my_object = MyClass()).
Q.7) What is abstraction in OOP?
● Answer: [A] Showing only essential details
● Explanation: Abstraction is the concept of hiding complex implementation details from
the user and exposing only the relevant and essential features of an object or system. It
helps manage complexity by providing a simplified view and focusing on what an object
does rather than how it does it.
Q.8) What is a class?
● Answer: [B] A blueprint for objects
● Explanation: A class is a user-defined blueprint or prototype from which objects are
created. It defines a set of attributes that characterize any object of the class and
methods that operate on those attributes.
Q.9) What does the self keyword represent?
● Answer: [B] The instance of the class
● Explanation: In Python class methods, self is a conventional name for the first
parameter. It refers to the instance of the class on which the method is being called.
Through self, a method can access the attributes and other methods of that particular
instance.
Q.10) What is a method in a class?
● Answer: [B] A function defined in a class
● Explanation: A method is a function that is defined inside a class and is associated with
objects of that class (instance methods) or the class itself (class methods or static
methods). Methods define the behaviors of the objects.
Q.11) What is a constructor in OOP?
● Answer: [B] A method that initializes objects
● Explanation: A constructor is a special type of method within a class that is
automatically invoked when an object of that class is created. Its main role is to initialize
the object's attributes to their default or user-specified values. In Python, the __init__
method serves as the constructor.
Q.12) What is a destructor in OOP?
● Answer: [B] A method that deletes objects
● Explanation: A destructor is a special method that is called automatically when an
object is about to be destroyed or deallocated (e.g., when it goes out of scope or is
garbage collected). It is used to perform cleanup tasks, such as releasing resources
(like file handles or network connections) that the object might have acquired during its
lifetime. In Python, __del__ is the destructor.
Q.13) How do you declare a private attribute in Python?
● Answer: [B] Using double underscores __var
● Explanation: Python doesn't have true "private" attributes in the same way as
languages like Java or C++. However, by prefixing an attribute name with double
underscores (e.g., __my_variable), Python performs "name mangling." This changes the
attribute's name internally to _ClassName__my_variable, making it harder to access
directly from outside the class and serving as a strong convention to indicate that the
attribute is intended for internal use.
Q.14) What is multiple inheritance?
● Answer: [B] Inheriting from two or more classes
● Explanation: Multiple inheritance is a feature of some object-oriented programming
languages where a class can inherit attributes and methods from more than one parent
class. This allows a class to combine functionalities from multiple sources.
Q.15) What is method overloading?
● Answer: [A] Defining methods with the same name
● Explanation: Method overloading refers to the ability to define multiple methods in the
same class with the same name but with different parameters (i.e., a different number of
parameters or different types of parameters). Python does not support traditional
method overloading in the same way as C++ or Java. Instead, similar functionality can
be achieved using default arguments, variable-length argument lists (*args, **kwargs),
or type checking within a single method.
Q.16) What is method overriding?
● Answer: [B] Redefining a method in a subclass
● Explanation: Method overriding occurs when a subclass (child class) provides a
specific implementation for a method that is already defined in its superclass (parent
class). The overridden method in the subclass must have the same name, and often the
same parameters and return type (or compatible ones), as the method in the
superclass.
Q.17) What is a static method in a class?
● Answer: [A] A method that doesn't require self
● Explanation: A static method is a method that belongs to the class rather than an
instance of the class. It is defined using the @staticmethod decorator in Python. It does
not receive an implicit first argument (like self for instance methods or cls for class
methods). Static methods cannot modify object state or class state directly but are
often utility functions related to the class.
Q.18) What is the purpose of the super() function?
● Answer: [A] Calls the parent class constructor
● Explanation: The super() function is used in a subclass to call methods of its
superclass. It's commonly used to invoke the superclass's constructor (e.g.,
super().__init__()) or any other method from the superclass that has been overridden in
the subclass, allowing you to extend rather than completely replace the superclass's
behavior.
Q.19) What does isinstance() check?
● Answer: [B] If a variable is an instance of a class
● Explanation: The isinstance(object, classinfo) built-in function in Python checks if the
object argument is an instance of the classinfo argument or an instance of a subclass
thereof. It returns True if it is, and False otherwise.
Q.20) What does the @property decorator do?
● Answer: [B] Declares a read-only property
● Explanation: The @property decorator in Python is used to define a method that can
be accessed like an attribute (i.e., without calling it with parentheses). It's primarily used
to create "getter" methods, providing controlled access to an attribute. While it can be
combined with @<property_name>.setter and @<property_name>.deleter to define write
and delete access, by itself, it effectively creates a read-only property.
Q.21) What is a class variable?
● Answer: [B] A variable shared by all instances
● Explanation: A class variable is declared inside a class definition but outside of any
instance methods. It is shared among all instances (objects) of that class. If one
instance changes the class variable (by accessing it through the class), the change is
reflected in all other instances.
Q.22) What is an instance variable?
● Answer: [C] A variable unique to each object
● Explanation: An instance variable is defined within a class's methods, typically within
the constructor (__init__), and is prefixed with self. Each object (instance) of the class
has its own distinct copy of instance variables, so their values are unique to each object.
Q.23) What is the main purpose of OOP?
● Answer: [A] To create reusable code
● Explanation: While OOP offers many benefits like better data organization, modularity,
and easier maintenance, one of its primary goals is to create reusable code. Features
like inheritance and composition allow developers to reuse existing code and build upon
it, reducing redundancy and development time.
Q.24) What is the result of encapsulation?
● Answer: [B] Data hiding
● Explanation: Encapsulation bundles data with the methods that operate on it and often
involves restricting direct access to the data (data hiding). This protects the internal
state of an object from unintended external modification, making the code more robust
and maintainable.
Q.25) What is a mixin in Python?
● Answer: [C] A type of class
● Explanation: A mixin is a class that provides a specific set of methods and attributes
intended to be inherited by other classes, but it's not designed to be instantiated on its
own. Mixins are used to add common functionalities to multiple classes without using
deep inheritance hierarchies, often through multiple inheritance.
Q.26) Which keyword is used to inherit a class?
● Answer: [D] None of the above
● Explanation: In Python, class inheritance is specified by placing the name of the parent
class (or classes, for multiple inheritance) in parentheses after the child class name in
its definition. For example: class ChildClass(ParentClass):. There isn't a specific keyword
like inherit or super used for the declaration itself.
Q.27) What is duck typing in Python?
● Answer: [B] Checking behavior rather than type
● Explanation: Duck typing is a concept common in dynamically-typed languages like
Python. It means that an object's suitability for a particular operation is determined by
whether it exhibits the necessary methods and properties ("if it walks like a duck and
quacks like a duck, then it must be a duck"), rather than by its explicit type or class
inheritance.
Q.28) What is the purpose of the __str__ method?
● Answer: [A] Convert the object to a string
● Explanation: The __str__ method in a Python class is a special method that should
return a string representation of an object. This method is called by the built-in str()
function and by the print() function to get an "informal" or nicely printable string
representation of the object, intended for end-users.
Q.29) What is an abstract class?
● Answer: [B] A class that cannot be instantiated
● Explanation: An abstract class is a class that is designed to be a blueprint for other
classes and cannot be instantiated on its own. It may contain one or more abstract
methods, which are declared but not implemented in the abstract class. Subclasses are
then required to provide implementations for these abstract methods.
Q.30) What is the purpose of the __del__ method?
● Answer: [B] Deletes an object
● Explanation: The __del__ method in Python is a destructor. It is called when an object is
about to be garbage collected (i.e., when all references to it have been removed). Its
purpose is to perform any necessary cleanup operations before the object's memory is
reclaimed, such as releasing external resources.
Q.31) What is a metaclass in Python?
● Answer: [A] A class of classes
● Explanation: A metaclass is the "class of a class." Just as a class defines how instances
(objects) of that class behave, a metaclass defines how classes themselves behave. The
default metaclass in Python is type. Metaclasses are an advanced topic used for
customizing class creation.
Q.32) What is composition in OOP?
● Answer: [B] Using other classes within a class
● Explanation: Composition is a design principle in OOP where a class (the composite) is
made up of instances of other classes (the components). This represents a "has-a"
relationship (e.g., a Car has an Engine). It's an alternative to inheritance for achieving
code reuse and building complex objects.
Q.33) What is the difference between is and == in Python?
● Answer: [B] is checks identity, == checks value
● Explanation:
○ is: This operator checks for object identity. It returns True if two variables point to
the exact same object in memory.
○ ==: This operator checks for equality of values. It returns True if the values of the
two objects are considered equal, as defined by the class's __eq__ method.
Q.34) How do you create a class method in Python?
● Answer: [B] Using @classmethod
● Explanation: A class method is created by using the @classmethod decorator above its
definition. A class method receives the class itself as its first implicit argument,
conventionally named cls. It can access and modify class state but not instance-specific
state.
Q.35) What is the purpose of __repr__ method?
● Answer: [B] For debugging string representation
● Explanation: The __repr__ method in a Python class should return an "official" or
unambiguous string representation of an object. This representation is primarily
intended for developers and debugging. Ideally, eval(repr(obj)) == obj. It's called by the
built-in repr() function and by the interactive interpreter when an expression's value is
displayed.
Q.36) What is the primary benefit of inheritance?
● Answer: [A] Code reusability
● Explanation: Inheritance allows new classes to reuse attributes and methods from
existing classes. This reduces code duplication, promotes a more organized code
structure, and makes it easier to manage and extend software.
Q.37) What is the purpose of the __dict__ attribute in a class?
● Answer: [B] Stores instance attributes
● Explanation: For an instance of a class, the __dict__ attribute is a dictionary that stores
the instance's writable attributes (its namespace). For a class itself, __dict__ stores the
class's attributes, including methods and class variables.
Q.38) Which keyword is used to declare a class attribute?
● Answer: [C] cls (This is conventionally used as the first parameter in class methods to
refer to the class itself, allowing access to class attributes. Class attributes themselves
are declared directly in the class scope without a specific keyword like cls.)
● Explanation: Class attributes are declared directly within the class definition, outside of
any methods. For example: class MyClass: class_var = 10. The identifier cls is the
conventional name for the first parameter of a class method (decorated with
@classmethod), which refers to the class itself. Through cls, class methods can access
or modify class attributes (e.g., cls.class_var).
Q.39) What is an interface in OOP?
● Answer: [B] A class with method definitions only
● Explanation: An interface defines a contract for what methods a class must implement,
without specifying how they are implemented. It typically consists of method signatures
(name, parameters, return type). In Python, interfaces are often implemented informally
through "duck typing" or more formally using Abstract Base Classes (ABCs) from the
abc module, where methods can be marked as abstract.
Q.40) What is the role of a destructor?
● Answer: [B] Deletes objects
● Explanation: The role of a destructor (e.g., __del__ in Python) is to perform cleanup
operations when an object is about to be destroyed or garbage collected. This can
include releasing resources like file handles, database connections, or network sockets.
Q.41) What does the term "instance" refer to in OOP?
● Answer: [C] An object created from a class
● Explanation: An instance is a concrete realization of a class. When a class is defined,
no memory is allocated until an object (instance) of that class is created. Each instance
has its own set of instance variables.
Q.42) What is the purpose of the __call__ method in a class?
● Answer: [A] Makes an object callable
● Explanation: If a class defines a __call__(self, *args, **kwargs) method, then instances
of that class can be "called" as if they were functions, using parentheses. For example,
if obj is an instance of such a class, obj(arg1, arg2) would execute the __call__ method.
Q.43) How do you prevent a class from being inherited?
● Answer: [C] Using final (This concept is from languages like Java or C#. Python does
not have a direct final keyword for classes.)
● Explanation: Python does not have a built-in final keyword to directly prevent a class
from being inherited, unlike languages such as Java or C#. However, one can achieve a
similar effect through more advanced techniques like using metaclasses or by raising an
exception in the __init_subclass__ method of the base class if an attempt is made to
subclass it. Among the given options, final refers to the concept in other OOP
languages.
Q.44) What is the main difference between a class and an object?
● Answer: [C] A class is a blueprint; an object is an instance
● Explanation: A class is a logical construct, a template, or a blueprint that defines
characteristics and behaviors. An object is a physical instance of that class, an entity
that exists in memory and has its own state (values for its attributes) based on the class
definition.
Q.45) What is a singleton class?
● Answer: [B] A class with only one instance
● Explanation: A singleton is a design pattern that restricts the instantiation of a class to
a single object. This ensures that there is only one instance of the class throughout the
application, providing a global point of access to it.
Q.46) What does the term "object identity" mean?
● Answer: [B] The memory address of the object
● Explanation: Object identity refers to a unique identifier for an object that distinguishes
it from all other objects. In Python, the id() function returns this identity, which is
typically the object's memory address during its lifetime.
Q.47) What is the purpose of the __new__ method in Python?
● Answer: [C] Creates a new instance of a class
● Explanation: __new__ is a special static method in Python that is responsible for
creating and returning a new, uninitialized instance of a class. It is called before __init__.
It's used less commonly than __init__, typically when you need to control the creation
process itself, such as in implementing singletons or when subclassing immutable types
like strings or numbers.
Q.48) What is the purpose of the __slots__ attribute in a class?
● Answer: [A] Limits instance attributes
● Explanation: By defining a __slots__ class variable (usually as a tuple of strings), you
can tell Python not to use a __dict__ for instances of that class, and instead, only
allocate space for a fixed set of attributes named in __slots__. This can lead to memory
savings and faster attribute access, but it also means instances cannot have attributes
other than those listed in __slots__.
Q.49) What is method resolution order (MRO)?
● Answer: [C] The order in which classes are inherited (More accurately, the order in
which base classes are searched for a method or attribute)
● Explanation: Method Resolution Order (MRO) defines the sequence in which Python
searches for attributes and methods in a class hierarchy, especially in the context of
multiple inheritance. Python uses an algorithm called C3 linearization to determine a
consistent and predictable MRO.
Q.50) What is the role of an abstract method in a class?
● Answer: [B] Defines a method without implementation
● Explanation: An abstract method is a method that is declared in an abstract class (a
class that cannot be instantiated) but does not have an implementation in that abstract
class. Subclasses that inherit from the abstract class are typically required to provide
concrete implementations for all its abstract methods. This enforces a common
interface across different implementations.
Test 2: Stack & Queue
Q.1) Which of the following is true about a stack?
● Answer: [A] LIFO (Last In, First Out)
● Explanation: A stack is a linear data structure that adheres to the Last-In, First-Out
(LIFO) principle. This means the element that was most recently added to the stack is
the first one to be removed.
Q.2) What operation is used to add an element to a stack?
● Answer: [A] Push
● Explanation: The push operation is used to add (or insert) an element onto the top of
the stack.
Q.3) What operation is used to remove an element from a stack?
● Answer: [B] Pop
● Explanation: The pop operation is used to remove and return the element currently at
the top of the stack.
Q.4) In which situation is a stack particularly useful?
● Answer: [A] Undo operations in a text editor
● Explanation: Stacks are useful in various scenarios, including:
○ Managing function calls (the call stack).
○ Parsing expressions (e.g., converting infix to postfix).
○ Implementing backtracking algorithms, such as undo functionality in editors or
solving mazes.
○ Depth-First Search (DFS) in graph and tree traversals.
Q.5) What is the result of popping an element from an empty stack?
● Answer: [A] Stack underflow
● Explanation: Attempting to perform a pop operation on an empty stack is an error
condition known as "stack underflow." This usually results in an exception being thrown
or an error code being returned.
Q.6) Which of the following is a real-world example of a stack?
● Answer: [D] Undo functionality in text editors
● Explanation:
○ Undo functionality: Each action is pushed onto a stack; "undo" pops the last
action.
○ Browser history (for the "back" button): Pages visited are pushed onto a stack.
○ A pile of plates: You add (push) to the top and remove (pop) from the top.
○ (Note: A print queue [B] is an example of a queue, not a stack.)
Q.7) Which data structure is used in function calls?
● Answer: [B] Stack
● Explanation: Operating systems and programming language runtimes use a "call stack"
(or execution stack) to manage function calls. When a function is called, a new frame
containing its local variables and return address is pushed onto the stack. When the
function returns, its frame is popped.
Q.8) What is the primary advantage of using a stack?
● Answer: [A] Quick access to the most recently added element
● Explanation: Due to its LIFO nature, the element at the top of the stack (the most
recently added one) can be accessed (peeked) or removed (popped) very quickly,
typically in constant time, O(1).
Q.9) Which algorithm is implemented using a stack?
● Answer: [A] Depth-First Search
● Explanation: Depth-First Search (DFS) for traversing or searching tree and graph data
structures often uses a stack (either explicitly managed by the programmer or implicitly
through recursion via the call stack) to keep track of the nodes to visit.
Q.10) What happens if you try to pop from an empty stack?
● Answer: [A] Stack underflow (or [D] An exception is thrown, depending on the specific
implementation)
● Explanation: This condition is called stack underflow. Most programming environments
will signal this error by raising an exception.
Q.11) What is the space complexity of a stack?
● Answer: [B] O(n)
● Explanation: The space complexity of a stack is O(n), where 'n' is the number of
elements currently stored in the stack. This is because the stack needs to store each of
these 'n' elements.
Q.12) Which of the following operations is not performed in a stack?
● Answer: [D] Search
● Explanation: Standard stack operations include push (add to top), pop (remove from
top), and peek or top (view top element). Stacks are not designed for efficient searching
of an arbitrary element within the stack. To find an element, one would typically have to
pop elements until it's found, which alters the stack and is an O(n) operation in the
worst case.
Q.13) How do you check if a stack is full?
● Answer: [A] Check if the top pointer is equal to the maximum size
● Explanation: This applies to array-based implementations of a stack where a fixed
maximum size (capacity) is defined. If the 'top' index or pointer reaches this maximum
capacity, the stack is considered full. For dynamically sized stacks (e.g., linked list
based), they are theoretically never "full" unless system memory is exhausted.
Q.14) Which data structure is used in depth-first traversal of a graph?
● Answer: [B] Stack
● Explanation: Depth-First Search (DFS) uses a stack to keep track of the vertices to
visit. It explores as far as possible along each branch before backtracking.
Q.15) What does the peek operation do in a stack?
● Answer: [B] Returns the top element without removing it
● Explanation: The peek (often called top) operation allows you to inspect the value of
the element at the top of the stack without actually removing it from the stack.
Q.16) Which of the following is true about a stack-based memory allocation?
● Answer: [A] Memory is allocated in a last-in-first-out order
● Explanation: Stack memory, used for storing local variables and function call
information, is managed in a LIFO manner. When a function is called, memory for its
variables is allocated (pushed); when it returns, this memory is deallocated (popped).
Q.17) What is the time complexity of the push and pop operations in a stack?
● Answer: [A] O(1)
● Explanation: For typical implementations of a stack (using arrays or linked lists), both
push and pop operations take constant time, O(1), on average and in the worst case,
because they only involve manipulating the top of the stack.
Q.18) Which of the following is true about a queue?
● Answer: [A] FIFO (First In, First Out)
● Explanation: A queue is a linear data structure that adheres to the First-In, First-Out
(FIFO) principle. This means the element that was first added to the queue is the first
one to be removed.
Q.19) What operation is used to add an element to a queue?
● Answer: [A] Enqueue
● Explanation: The enqueue operation (sometimes called add or offer) is used to add an
element to the rear (or tail) of the queue.
Q.20) What operation is used to remove an element from a queue?
● Answer: [D] Dequeue
● Explanation: The dequeue operation (sometimes called remove or poll) is used to
remove and return the element from the front (or head) of the queue.
Q.21) In which situation is a queue particularly useful?
● Answer: [A] Scheduling tasks in a processor
● Explanation: Queues are useful in situations where items need to be processed in the
order they arrive, such as:
○ Task scheduling in operating systems (e.g., CPU scheduling, print queues).
○ Breadth-First Search (BFS) in graph and tree traversals.
○ Buffering data (e.g., in streaming).
○ Serving requests in order (e.g., a line of customers).
Q.22) What is the result of dequeuing an element from an empty queue?
● Answer: [A] Queue underflow
● Explanation: Attempting to perform a dequeue operation on an empty queue is an error
condition known as "queue underflow." This usually results in an exception or an error
code.
Q.23) Which of the following is a real-world example of a queue?
● Answer: [A] Printer queue
● Explanation: A printer queue processes print jobs in the order they were submitted
(FIFO). Other examples include customer service call queues or lines at a checkout
counter.
Q.24) Which data structure is used in breadth-first search?
● Answer: [B] Queue
● Explanation: Breadth-First Search (BFS) for traversing or searching tree and graph
data structures uses a queue to keep track of the nodes to visit. BFS explores nodes
level by level.
Q.25) What is the primary advantage of using a queue?
● Answer: [A] Quick access to the least recently added element
● Explanation: Due to its FIFO nature, the element at the front of the queue (the least
recently added one, or the "oldest" one) is always the next to be processed. It can be
accessed (peeked) or removed (dequeued) efficiently, typically in O(1) time.
Q.26) Which algorithm is implemented using a queue?
● Answer: [B] Breadth-First Search
● Explanation: Breadth-First Search (BFS) uses a queue to manage the order of visiting
nodes, ensuring that all nodes at a given depth are visited before moving to the next
depth level.
Q.27) What happens if you try to dequeue from an empty queue?
● Answer: [A] Queue underflow (or [D] An exception is thrown, depending on the
implementation)
● Explanation: This condition is called queue underflow. Most programming
environments will signal this error by raising an exception.
Q.28) What is the space complexity of a queue?
● Answer: [B] O(n)
● Explanation: The space complexity of a queue is O(n), where 'n' is the number of
elements currently stored in the queue, as it needs to store each element.
Q.29) Which of the following operations is not performed in a queue?
● Answer: [D] Search
● Explanation: Standard queue operations include enqueue (add to rear), dequeue
(remove from front), and peek or front (view front element). Queues are not designed
for efficient searching of arbitrary elements.
Q.30) How do you check if a queue is full?
● Answer: [A] Check if the rear pointer is equal to the maximum size (This applies to
simple array-based queues. Circular queues have more nuanced conditions.)
● Explanation: For a fixed-size array implementation of a queue, it's considered full when
no more elements can be added. In a simple (non-circular) array queue, this might
happen when the rear pointer reaches the array's capacity. In a circular queue, the
condition is typically when (rear + 1) % capacity == front (if rear points to the last
element) or based on a separate size counter.
Q.31) Which data structure is used in breadth-first traversal of a graph?
● Answer: [A] Queue
● Explanation: Breadth-First Search (BFS) uses a queue to explore graph nodes layer by
layer.
Q.32) What is the time complexity of enqueue and dequeue operations in a queue?
● Answer: [A] O(1)
● Explanation: For well-implemented queues (e.g., using a linked list or a circular array),
both enqueue and dequeue operations typically take constant time, O(1).
Q.33) What is the purpose of a circular queue?
● Answer: [A] To overcome the limitation of fixed-size queue
● Explanation: A circular queue is an efficient way to implement a queue using a
fixed-size array. It allows the queue to wrap around to the beginning of the array when
the end is reached, effectively reusing empty slots at the front of the array that were
vacated by dequeue operations. This prevents the "false full" state that can occur in
simple linear array queues.
Q.34) Which of the following is an application of a queue?
● Answer: [A] Job scheduling in operating systems
● Explanation: Queues are widely used in operating systems for managing processes
waiting for resources like the CPU (ready queue), I/O devices (I/O queues), etc.
Q.35) What is the condition for queue overflow?
● Answer: [A] When the rear pointer exceeds the maximum size (This is a simplified view.
More generally, it's when the queue is at its maximum capacity and an enqueue
operation is attempted.)
● Explanation: Queue overflow occurs when an attempt is made to add an element to a
queue that is already full (i.e., has reached its maximum capacity).
Q.36) Which data structure is used in implementing a queue in most programming
languages?
● Answer: [B] Linked list (or [A] Array, often as a circular array)
● Explanation: Queues can be implemented using either arrays (often as circular arrays
for efficiency) or linked lists. Linked lists offer dynamic resizing more easily, while arrays
can be more memory-efficient if the maximum size is known and can provide better
cache performance in some cases.
Q.37) What is a priority queue?
● Answer: [A] A queue in which elements are dequeued based on their priority
● Explanation: A priority queue is an abstract data type where each element has an
associated "priority." Elements with higher priority are served (dequeued) before
elements with lower priority. If two elements have the same priority, their relative order
might be determined by FIFO or other rules.
Q.38) What is a double-ended queue (deque)?
● Answer: [A] A queue where elements can be inserted or removed from both ends
● Explanation: A deque (pronounced "deck"), short for double-ended queue, is a
generalization of a queue where elements can be added (enqueued) or removed
(dequeued) from either the front (head) or the rear (tail).
Q.39) Which of the following is true about stack memory?
● Answer: [C] Stack memory is used for function calls and local variables
● Explanation: Stack memory is a region of computer memory used for static memory
allocation, primarily for storing local variables of functions and managing the flow of
execution through function calls (call stack). It operates in a LIFO manner.
Q.40) Which operation can be performed on a stack to check the value of the top
element without removing it?
● Answer: [A] Peek
● Explanation: The peek (or top) operation allows inspection of the top element of the
stack without modifying the stack.
Q.41) What is the maximum number of elements that can be stored in a stack of size 'n'?
● Answer: [B] n
● Explanation: If a stack is defined with a capacity or size of 'n', it means it can hold up to
'n' elements.
Q.42) In a stack, what happens when an element is pushed beyond the allocated
memory?
● Answer: [A] Stack overflow
● Explanation: If you attempt to push an element onto a stack that is already full (has
reached its capacity), a "stack overflow" error occurs.
Q.43) Which of the following is an application of stack?
● Answer: [A] Expression evaluation
● Explanation: Stacks are commonly used in the evaluation of arithmetic expressions,
particularly for converting expressions from infix notation to postfix (or prefix) notation
and then evaluating the postfix expression.
Q.44) What is the result of trying to pop an element from a stack when it is empty?
● Answer: [A] Stack underflow
● Explanation: This is the definition of stack underflow.
Q.45) Which of the following is an example of a stack?
● Answer: [A] Browser's back button
● Explanation: The functionality of a web browser's "back" button is typically
implemented using a stack, where each visited page URL is pushed onto the stack.
Q.46) What happens when the stack pointer exceeds its limit?
● Answer: [A] Stack overflow
● Explanation: If the stack pointer (which indicates the top of the stack in an array
implementation) goes beyond the allocated boundary for the stack, it signifies a stack
overflow.
Q.47) Which of the following operations is used to remove an element from the stack?
● Answer: [A] Pop
● Explanation: The pop operation removes the top element.
Q.48) What is the time complexity for push and pop operations in a stack?
● Answer: [A] O(1)
● Explanation: These operations are typically O(1).
Q.49) In a queue, which pointer is used to remove an element?
● Answer: [A] Front pointer
● Explanation: The front (or head) pointer in a queue indicates the position of the
element that will be removed next by a dequeue operation.
Q.50) Which of the following is a characteristic of a queue?
● Answer: [A] FIFO (First In, First Out)
● Explanation: FIFO is the defining characteristic of a queue.
Test 3: Linked List, Tree & Graph
Q.1) Which of the following is true about a linked list?
● Answer: [B] It stores elements in non-contiguous memory
● Explanation: In a linked list, elements (nodes) are not necessarily stored in adjacent
memory locations. Each node contains data and a pointer (or link) to the next node in
the sequence, allowing them to be scattered in memory.
Q.2) What is the main advantage of a linked list over an array?
● Answer: [A] Dynamic memory allocation
● Explanation: Linked lists offer dynamic sizing; they can easily grow or shrink at runtime
as elements are added or removed because memory for each node is allocated
individually. Arrays, in contrast, typically have a fixed size determined at creation
(though some languages offer dynamic arrays that reallocate internally). Efficient
insertion/deletion in the middle is another advantage if the node is known.
Q.3) What does a singly linked list consist of?
● Answer: [A] Nodes with two fields: data and a reference to the next node
● Explanation: Each node in a singly linked list typically contains two parts: one to store
the actual data (the element) and another to store a reference (or pointer) to the next
node in the list. The last node's reference points to null.
Q.4) In a singly linked list, how do you access the last element?
● Answer: [A] By traversing the list from the head
● Explanation: To find the last element in a singly linked list, you must start from the head
(the first node) and follow the next pointers of each subsequent node until you reach a
node whose next pointer is null. This node is the last element.
Q.5) What is the time complexity for inserting an element at the beginning of a singly
linked list?
● Answer: [A] O(1)
● Explanation: Inserting an element at the beginning of a singly linked list involves:
1. Creating a new node.
2. Setting the next pointer of the new node to point to the current head of the list.
3. Updating the head of the list to be the new node.
All these steps take constant time.
Q.6) Which of the following is not a type of linked list?
● Answer: [A] Binary linked list
● Explanation: Standard types of linked lists include singly linked lists, doubly linked lists,
and circular linked lists. "Binary linked list" is not a standard term for a type of linked list;
it might be confused with how binary trees can be implemented using linked nodes
where each node has up to two child pointers.
Q.7) Which operation is performed to remove an element from the end of a singly linked
list?
● Answer: [B] Delete
● Explanation: To delete the last element of a singly linked list, you need to:
1. Traverse the list to find the second-to-last node (this takes O(n) time).
2. Set the next pointer of the second-to-last node to null.
3. Deallocate the memory of the original last node.
The operation itself is deletion, but it requires traversal.
Q.8) What is the primary disadvantage of a singly linked list?
● Answer: [B] It does not support fast random access
● Explanation: To access an element at a specific position (index) in a singly linked list,
you must traverse the list from the head node sequentially. This means random access
has a time complexity of O(n) in the worst case, unlike arrays which offer O(1) random
access.
Q.9) What is a doubly linked list?
● Answer: [A] A list where each node has a reference to the next and previous node
● Explanation: In a doubly linked list, each node contains three fields: one for the data,
one for a reference (pointer) to the next node in the list, and one for a reference
(pointer) to the previous node in the list. This allows for traversal in both forward and
backward directions.
Q.10) What happens when you attempt to access a node that is out of bounds in a
linked list?
● Answer: [A] Null reference error
● Explanation: If you try to traverse beyond the end of a linked list (e.g., accessing
some_node.next when some_node is the last node and its next is null), and then attempt
to dereference that null pointer, it typically results in a null reference error (or
NullPointerException, segmentation fault, depending on the language and environment).
Q.11) Which operation is used to reverse a linked list?
● Answer: [A] Reversal
● Explanation: Reversing a linked list is an operation that changes the direction of the
links between nodes, so that the original tail becomes the new head and vice-versa, and
all next pointers point in the opposite direction. This can be done iteratively or
recursively.
Q.12) Which of the following is true about a circular linked list?
● Answer: [A] The last node points back to the first node
● Explanation: In a circular linked list, the next pointer of the last node in the list points
back to the head (the first node) of the list, forming a closed loop or circle.
Q.13) What is the space complexity of a singly linked list?
● Answer: [A] O(n)
● Explanation: A singly linked list with 'n' elements requires space proportional to 'n'
because each node stores data and a pointer to the next node.
Q.14) How can you detect a loop in a linked list?
● Answer: [A] By using Floyd’s cycle-finding algorithm
● Explanation: Floyd's cycle-finding algorithm, also known as the "tortoise and hare"
algorithm, is a common method. It uses two pointers that traverse the list at different
speeds. If the list has a loop, the faster pointer will eventually catch up to and meet the
slower pointer. Other methods include hashing node addresses or marking visited
nodes.
Q.15) What is the primary use case for a linked list?
● Answer: [A] Dynamic memory allocation (More accurately, situations requiring frequent
insertions/deletions and dynamic sizing)
● Explanation: Linked lists are particularly useful when the number of elements to be
stored is not known in advance, or when frequent insertions and deletions are required,
especially in the middle of the list (for which doubly linked lists are more efficient than
singly linked lists if the node itself is known). Their ability to allocate memory
dynamically per node is a key feature.
Q.16) Which of the following is a property of a binary tree?
● Answer: [A] Each node has at most two children
● Explanation: A binary tree is a hierarchical data structure in which each node can have
a maximum of two children, typically referred to as the left child and the right child.
Q.17) What is the height of a binary tree?
● Answer: [A] The number of edges on the longest path from root to leaf
● Explanation: The height of a binary tree is defined as the number of edges on the
longest path from the root node to any leaf node. The height of an empty tree is often
considered -1, and a tree with a single node (root only) has a height of 0.
Q.18) In a binary search tree (BST), which of the following is true?
● Answer: [A] Left child < parent < right child (Assuming distinct values, or more precisely,
all values in the left subtree are less than the parent, and all values in the right subtree
are greater than the parent.)
● Explanation: The fundamental property of a Binary Search Tree (BST) is that for any
given node:
○ All values in its left subtree are less than the node's value.
○ All values in its right subtree are greater than the node's value.
(Handling of duplicate values can vary by implementation, e.g., allowing them in
only one subtree or not at all.)
Q.19) Which of the following traversal methods visits the root node last?
● Answer: [A] Postorder
● Explanation:
○ Preorder: Root -> Left Subtree -> Right Subtree
○ Inorder: Left Subtree -> Root -> Right Subtree
○ Postorder: Left Subtree -> Right Subtree -> Root
Therefore, postorder traversal visits the root node last.
Q.20) What is the worst-case time complexity of searching in a balanced binary search
tree?
● Answer: [A] O(log n)
● Explanation: In a balanced Binary Search Tree (like AVL or Red-Black trees), the height
of the tree is proportional to log n, where n is the number of nodes. Since searching
involves traversing from the root down to a leaf in the worst case, the time complexity is
O(log n).
Q.21) What is a full binary tree?
● Answer: [A] A tree where every node has either 0 or 2 children
● Explanation: A full binary tree (sometimes called a proper binary tree) is a tree in which
every node has either zero children (it's a leaf node) or exactly two children. No node
has only one child.
Q.22) Which of the following is true about a heap?
● Answer: [A] It is a complete binary tree
● Explanation: A heap is a specialized tree-based data structure that satisfies the heap
property (e.g., in a min-heap, the value of each node is less than or equal to the values
of its children; in a max-heap, it's greater than or equal). Structurally, heaps are typically
implemented using an array and are maintained as a complete binary tree. A complete
binary tree is a binary tree in which all levels are completely filled except possibly the
last level, which is filled from left to right.
Q.23) In a binary tree, which traversal method gives nodes in increasing order? (This is
specifically true for a Binary Search Tree, not just any binary tree)
● Answer: [A] Inorder
● Explanation: For a Binary Search Tree (BST), performing an inorder traversal (Left
Subtree -> Root -> Right Subtree) visits the nodes in ascending order of their values.
This property does not necessarily hold for a general binary tree that is not a BST.
Q.24) What is a balanced tree?
● Answer: [A] A tree where the height difference between the left and right subtrees of
any node is at most 1
● Explanation: This definition specifically describes an AVL tree, which is a type of
self-balancing binary search tree. More generally, a "balanced tree" is one whose
height is kept logarithmically proportional to the number of nodes (O(log n)). This
ensures efficient operations like search, insert, and delete.
Q.25) Which algorithm is used to construct a balanced binary tree?
● Answer: [A] AVL tree algorithm
● Explanation: AVL tree algorithms (and others like Red-Black tree algorithms) include
specific operations (like rotations) that are performed during insertions and deletions to
maintain the tree's balance criteria, ensuring that the height remains O(log n).
Q.26) What is a red-black tree?
● Answer: [A] A self-balancing binary search tree
● Explanation: A Red-Black tree is a type of self-balancing binary search tree. Each node
stores an extra bit representing its "color" (red or black). These colors are used to
enforce certain properties that guarantee the tree remains approximately balanced,
ensuring O(log n) time complexity for search, insert, and delete operations.
Q.27) Which of the following is true about a perfect binary tree?
● Answer: [A] All internal nodes have two children and all leaves are at the same level
● Explanation: A perfect binary tree is a binary tree in which all interior nodes have
exactly two children, and all leaf nodes are at the same depth (or level). This means the
tree is completely filled.
Q.28) What is the space complexity of a binary tree?
● Answer: [A] O(n)
● Explanation: A binary tree with 'n' nodes requires space proportional to 'n' to store the
data in each node and the pointers (references) to its children.
Q.29) What does the height of a tree represent?
● Answer: [A] The longest path from the root to a leaf node
● Explanation: The height of a tree is the number of edges on the longest path from the
root node to any leaf node.
Q.30) Which of the following operations is most efficiently performed on a binary
search tree?
● Answer: [A] Searching for an element (also [C] Inserting, [D] Deleting, all are O(log n) in
a balanced BST, O(n) worst case)
● Explanation: For a balanced Binary Search Tree, searching, insertion, and deletion
operations all have an average and worst-case time complexity of O(log n). If the BST is
unbalanced, these can degrade to O(n). Finding the height of a tree generally requires
traversing all nodes in the worst case, so it's O(n).
Q.31) Which of the following is not a characteristic of a graph?
● Answer: [C] A graph always contains a root node
● Explanation: The concept of a "root node" is specific to tree data structures (which are
a special type of graph). General graphs do not necessarily have a designated root
node. Graphs consist of vertices (nodes) and edges connecting them, and can be
directed/undirected and cyclic/acyclic.
Q.32) What is the primary use of depth-first search (DFS) in a graph?
● Answer: [A] Exploring all possible paths (More accurately, exploring as far as possible
along each branch before backtracking)
● Explanation: Depth-First Search (DFS) explores a graph by going as deep as possible
along each branch before backtracking. It's used for:
○ Finding connected components.
○ Topological sorting (for Directed Acyclic Graphs).
○ Detecting cycles.
○ Pathfinding (though not necessarily the shortest path).
Q.33) Which data structure is commonly used to implement a graph?
● Answer: [D] Adjacency list
● Explanation: The two most common ways to represent a graph in memory are:
○ Adjacency List: An array (or list) where each index i corresponds to vertex i, and
the element at that index is a list of vertices adjacent to vertex i.
○ Adjacency Matrix: A 2D matrix where matrix[i][j] = 1 (or some weight) if there's an
edge from vertex i to vertex j, and 0 otherwise.
Queues and stacks are used in graph traversal algorithms (BFS and DFS
respectively) but not typically for storing the graph structure itself.
Q.34) What is a directed graph?
● Answer: [A] A graph in which edges have a direction
● Explanation: In a directed graph (or digraph), edges have a specific direction
associated with them. An edge (u, v) means there is a connection from vertex u to
vertex v, but not necessarily from v to u.
Q.35) What is the time complexity of BFS for a graph with V vertices and E edges?
● Answer: [A] O(V+E)
● Explanation: Breadth-First Search (BFS) visits every vertex and every edge once. When
implemented using an adjacency list representation of the graph, its time complexity is
O(V + E), where V is the number of vertices and E is the number of edges.
Q.36) What is the difference between a tree and a graph?
● Answer: [A] A tree is a type of graph with no cycles (and is connected)
● Explanation: A tree is a specific type of graph that is:
1. Connected (there is a path between any two vertices).
2. Acyclic (it contains no cycles).
All trees are graphs, but not all graphs are trees. Option [D] "All of the above" is
also largely correct because if a graph has no cycles and is connected, it will have
a structure where a root can be designated (though not inherent to all graph
views).
Q.37) Which algorithm is used to find the shortest path in a graph?
● Answer: [A] Dijkstra’s algorithm
● Explanation:
○ Dijkstra's Algorithm: Finds the shortest path from a single source vertex to all
other vertices in a graph with non-negative edge weights.
○ Floyd-Warshall Algorithm: Finds all-pairs shortest paths (shortest path between
every pair of vertices). Can handle negative edge weights but not negative cycles.
○ Bellman-Ford Algorithm: Finds the shortest path from a single source and can
handle negative edge weights (and detect negative cycles).
○ Prim's algorithm is for finding a Minimum Spanning Tree.
Q.38) Which of the following is true about an acyclic graph?
● Answer: [A] It contains no cycles
● Explanation: An acyclic graph is, by definition, a graph that does not contain any cycles
(a path that starts and ends at the same vertex without repeating edges, and involves at
least three vertices for simple cycles).
Q.39) What is the space complexity of storing a graph in an adjacency matrix?
● Answer: [A] O(V^2)
● Explanation: An adjacency matrix representation of a graph with V vertices uses a V x V
matrix. Therefore, it always requires O(V^2) space, regardless of the actual number of
edges (E). This can be inefficient for sparse graphs (where E is much less than V^2).
Q.40) Which of the following is used to detect cycles in a directed graph?
● Answer: [B] DFS
● Explanation: Depth-First Search (DFS) can be used to detect cycles in a directed
graph. During a DFS traversal, if an edge is encountered that leads to a vertex already in
the current recursion stack (an ancestor), it indicates a back edge, which forms a cycle.
Topological sort [A] is only possible for Directed Acyclic Graphs (DAGs); if a topological
sort cannot be completed, it implies the graph has a cycle.
Q.41) What does a minimum spanning tree (MST) represent?
● Answer: [A] The smallest set of edges that connect all the vertices in a graph
● Explanation: For a connected, undirected, and weighted graph, a Minimum Spanning
Tree (MST) is a subgraph that includes all the vertices of the original graph, forms a tree
(is connected and acyclic), and has the minimum possible total sum of edge weights
among all such spanning trees.
Q.42) Which of the following algorithms is used to find a minimum spanning tree?
● Answer: [A] Kruskal’s algorithm
● Explanation: Common algorithms for finding an MST include:
○ Kruskal's Algorithm: Sorts all edges by weight and adds them to the MST if they
don't form a cycle.
○ Prim's Algorithm: Grows the MST from a starting vertex by iteratively adding the
cheapest edge connecting a vertex in the MST to one outside it.
Q.43) What is the degree of a vertex in a graph?
● Answer: [A] The number of edges connected to the vertex
● Explanation:
○ In an undirected graph, the degree of a vertex is the number of edges incident to
it.
○ In a directed graph, we distinguish between:
■ In-degree: The number of edges pointing into the vertex.
■ Out-degree: The number of edges pointing out from the vertex.
Q.44) Which of the following is true about a bipartite graph?
● Answer: [A] It can be colored using two colors
● Explanation: A graph is bipartite if its vertices can be divided into two disjoint and
independent sets, U and V, such that every edge connects a vertex in U to one in V.
Equivalently, a graph is bipartite if and only if it contains no odd-length cycles. Such
graphs are 2-colorable (meaning each vertex can be assigned one of two colors such
that no two adjacent vertices have the same color).
Q.45) What is the time complexity of searching for an element in a singly linked list?
● Answer: [B] O(n)
● Explanation: In the worst-case scenario (the element is the last one or not present at
all), you have to traverse the entire linked list of 'n' elements. Thus, the time complexity
for searching is O(n).
Q.46) What is the main disadvantage of a doubly linked list?
● Answer: [A] It uses more memory
● Explanation: Each node in a doubly linked list stores an extra pointer (to the previous
node) compared to a singly linked list. This means that doubly linked lists require more
memory per node.
Q.47) What happens when you delete the head node in a singly linked list?
● Answer: [A] The next node becomes the head
● Explanation: To delete the head node:
1. Store a reference to the current head's next node.
2. Deallocate or free the memory of the current head node.
3. Update the list's head pointer to now point to the node that was originally the
second node.
Q.48) Which of the following is true about a binary search tree (BST)?
● Answer: [C] The left child is smaller than the parent (and [D] The right child is always
greater than the parent, assuming distinct values and standard BST property)
● Explanation: The defining property of a BST is that for any node, all values in its left
subtree are less than the node's value, and all values in its right subtree are greater than
the node's value.
Q.49) What is the inorder traversal of a binary tree?
● Answer: [B] Visit the left subtree, then root, then right subtree
● Explanation: Inorder traversal follows the pattern:
1. Recursively traverse the left subtree.
2. Visit (e.g., print or process) the root node.
3. Recursively traverse the right subtree.
(Mnemonic: Left-Root-Right)
Q.50) Which of the following algorithms is used to balance a binary search tree?
● Answer: [A] AVL tree rotations
● Explanation: Self-balancing binary search trees like AVL trees and Red-Black trees use
specific operations, primarily rotations (e.g., single left, single right, double left-right,
double right-left rotations in AVL trees), to restructure the tree after insertions or
deletions to maintain its balance property and ensure O(log n) height.
Test 4: Searching & Sorting
Q.1) Which of the following searching algorithms is best suited for an unsorted array?
● Answer: [A] Linear search
● Explanation: Linear search iterates through each element of the array sequentially until
the target element is found or the end of the array is reached. It does not require the
array to be sorted. Algorithms like binary search, jump search, and interpolation search
require the array to be sorted.
Q.2) What is the time complexity of linear search?
● Answer: [C] O(n)
● Explanation: In the worst-case scenario (element is at the end or not present), linear
search has to examine all 'n' elements in the array. Therefore, its time complexity is O(n).
The best case is O(1) (element found at the beginning).
Q.3) Which of the following is true about binary search?
● Answer: [A] It works on sorted arrays
● Explanation: Binary search is an efficient algorithm that works by repeatedly dividing
the search interval in half. This process relies on the array being sorted. If the array is
not sorted, binary search will not produce correct results.
Q.4) What is the worst-case time complexity of binary search?
● Answer: [C] O(log n)
● Explanation: In each step, binary search reduces the search space by half. The number
of steps required is logarithmic with respect to the number of elements 'n'. Thus, its time
complexity is O(log n) for all cases (best, average, worst, though best is O(1) if the
element is found in the first comparison).
Q.5) Which searching algorithm has the best time complexity for large datasets?
● Answer: [B] Binary search (assuming the dataset is sorted or can be sorted efficiently
first)
● Explanation: For large, sorted datasets, binary search (O(log n)) is significantly faster
than linear search (O(n)). Jump search and exponential search also aim for better than
linear but are generally outperformed by binary search on typical sorted arrays.
Q.6) Which of the following is an advantage of binary search?
● Answer: [A] It is faster than linear search for large sorted arrays
● Explanation: The primary advantage of binary search is its efficiency (O(log n) time
complexity) when searching in large sorted arrays, making it much faster than the O(n)
complexity of linear search.
Q.7) Which search algorithm is used in case of a sorted array where elements are
uniformly distributed?
● Answer: [B] Interpolation search
● Explanation: Interpolation search is an improvement over binary search for sorted
arrays where the values are uniformly distributed. Instead of always checking the middle
element, it estimates the position of the target element based on its value relative to the
first and last elements in the current search interval. Its average time complexity can be
O(log log n) under uniform distribution, but its worst-case is O(n).
Q.8) What is the main disadvantage of binary search?
● Answer: [A] It only works on sorted arrays
● Explanation: The most significant limitation of binary search is that it requires the input
array to be sorted. If the array is not sorted, it must be sorted first, which adds an
overhead (e.g., O(n log n) for efficient sorting algorithms).
Q.9) What is the time complexity of binary search in the best case?
● Answer: [A] O(1)
● Explanation: The best-case scenario for binary search occurs when the target element
is the middle element of the array, which is found in the very first comparison. This takes
constant time, O(1).
Q.10) Which of the following searching algorithms works on a sorted and rotated array?
● Answer: [B] Binary search (modified)
● Explanation: A standard binary search won't work directly on a sorted but rotated array
(e.g., [4, 5, 6, 7, 0, 1, 2]). However, a modified version of binary search can be used. The
strategy involves first finding the pivot point (the point of rotation) and then performing
binary search on the appropriate sorted subarray.
Q.11) Which of the following searching algorithms is not comparison-based?
● Answer: [D] Interpolation search (This is generally considered comparison-based, as it
makes comparisons after probing. True non-comparison searches include hashing or
radix search, which are not options here. The question might be flawed.)
● Explanation:
○ Comparison-based searches (Linear, Binary, Jump, Interpolation) work by
comparing the target key with elements in the data structure.
○ Non-comparison searches (e.g., Hashing, Counting Sort based search, Radix
Search) use other properties of the keys, like their direct addressability or
digit/character values.
Interpolation search does use comparisons after it makes an educated guess
(interpolation) for the position. Perhaps the question implies the probing step is
not purely comparison, but the overall algorithm relies on comparisons. Given the
options, this is a tricky or potentially flawed question.
Q.12) Which searching algorithm works by checking the middle element and repeatedly
dividing the search interval in half?
● Answer: [A] Binary search
● Explanation: This is the fundamental working principle of the binary search algorithm.
Q.13) What is the best-case time complexity of linear search?
● Answer: [A] O(1)
● Explanation: The best case for linear search occurs when the target element is the very
first element in the array. In this situation, only one comparison is needed, resulting in
O(1) time complexity.
Q.14) Which search algorithm is used to find the position of an element in an array
where elements are sorted?
● Answer: [A] Binary search
● Explanation: Binary search is the standard and most efficient general-purpose
algorithm for searching in a sorted array.
Q.15) What type of search is performed when the array is not sorted and requires
sequential checking?
● Answer: [B] Linear search
● Explanation: This describes linear search, where each element is checked one by one
in sequence.
Q.16) Which sorting algorithm works by repeatedly finding the minimum element and
placing it at the beginning?
● Answer: [A] Selection sort
● Explanation: In each pass of selection sort, it finds the minimum element from the
unsorted portion of the array and swaps it with the element at the current position (the
beginning of the unsorted portion). This gradually builds the sorted part of the array
from left to right.
Q.17) What is the time complexity of bubble sort in the worst case?
● Answer: [C] O(n^2)
● Explanation: Bubble sort has a time complexity of O(n^2) in both the average and worst
cases. The worst case occurs when the array is sorted in reverse order, requiring the
maximum number of comparisons and swaps.
Q.18) Which sorting algorithm works by dividing the array into smaller sub-arrays and
then merging them?
● Answer: [B] Merge sort
● Explanation: Merge sort is a classic divide-and-conquer algorithm. It recursively
divides the input array into two halves until subarrays of size 1 (which are inherently
sorted) are reached. Then, it repeatedly merges these sorted subarrays to produce
larger sorted subarrays until the entire array is sorted.
Q.19) Which sorting algorithm works by dividing the array into two partitions and
recursively sorting them?
● Answer: [B] Quick sort
● Explanation: Quick sort is also a divide-and-conquer algorithm. It selects an element
as a "pivot," partitions the array around the pivot such that elements smaller than the
pivot are on its left and elements greater are on its right. Then, it recursively sorts the
subarrays to the left and right of the pivot.
Q.20) What is the time complexity of quicksort in the best case?
● Answer: [A] O(n log n)
● Explanation: The best-case (and average-case) time complexity for quicksort is O(n
log n). This occurs when the pivot selection consistently divides the array into two
nearly equal-sized partitions at each step.
Q.21) Which sorting algorithm is generally faster quicksort or merge sort?
● Answer: [A] Quicksort
● Explanation: While both quicksort and merge sort have an average time complexity of
O(n log n), quicksort is often faster in practice for typical inputs. This is due to factors
like better cache locality and lower constant factors in its operations. However,
quicksort's worst-case is O(n^2), whereas merge sort's worst-case is O(n log n).
Q.22) Which of the following sorting algorithms is not comparison-based?
● Answer: [C] Radix sort
● Explanation:
○ Comparison-based sorts (Merge sort, Quick sort, Selection sort, Bubble sort,
Insertion sort, Heap sort) determine the sorted order by comparing elements with
each other.
○ Non-comparison sorts, like Radix sort, Counting sort, and Bucket sort, work by
using other properties of the elements (e.g., digit values, key ranges) and do not
rely solely on element-to-element comparisons. Radix sort sorts integers by
processing individual digits.
Q.23) What is the worst-case time complexity of quicksort?
● Answer: [B] O(n^2)
● Explanation: The worst-case scenario for quicksort occurs when the pivot selection is
consistently poor, leading to highly unbalanced partitions. For example, if the pivot is
always the smallest or largest element in an already sorted or reverse-sorted array,
quicksort degrades to O(n^2).
Q.24) Which sorting algorithm works by swapping adjacent elements if they are in the
wrong order?
● Answer: [A] Bubble sort
● Explanation: Bubble sort repeatedly steps through the list, compares adjacent
elements, and swaps them if they are in the incorrect order (e.g., if the first is greater
than the second for ascending order). The largest (or smallest) elements "bubble" to
their correct positions.
Q.25) Which sorting algorithm is known for being the simplest to implement but
inefficient for large datasets?
● Answer: [A] Bubble sort
● Explanation: Bubble sort is often one of the first sorting algorithms taught due to its
conceptual simplicity. However, its O(n^2) time complexity makes it very inefficient for
sorting large lists compared to algorithms like merge sort or quicksort. Selection sort
and insertion sort also fit this description to some extent.
Q.26) Which of the following sorting algorithms has the best average-case time
complexity?
● Answer: [D] Quick sort (and [B] Merge sort)
● Explanation: Quicksort, Merge sort, and Heap sort all have an average-case time
complexity of O(n log n), which is optimal for comparison-based sorting algorithms.
Q.27) Which sorting algorithm has the worst time complexity of O(n^2)?
● Answer: [A] Selection sort (also Insertion sort, Bubble sort, and Quicksort in its worst
case)
● Explanation:
○ Selection sort: Always O(n^2).
○ Insertion sort: O(n^2) in average and worst cases (O(n) in best case).
○ Bubble sort: O(n^2) in average and worst cases (O(n) in best case with
optimization).
○ Quicksort: O(n^2) in its worst case.
○ Merge sort: Always O(n log n).
Q.28) Which of the following sorting algorithms is considered stable?
● Answer: [B] Merge sort
● Explanation: A sorting algorithm is stable if it preserves the relative order of equal
elements in the sorted output.
○ Stable: Merge sort, Insertion sort, Bubble sort (if implemented carefully), Timsort,
Counting sort.
○ Not Stable (generally): Quicksort, Heap sort, Selection sort.
Q.29) Which sorting algorithm can be implemented with a divide and conquer strategy?
● Answer: [A] Merge sort (also Quick sort)
● Explanation: Both Merge sort and Quick sort are classic examples of algorithms that
use the divide and conquer paradigm:
1. Divide: Break the problem into smaller subproblems.
2. Conquer: Solve the subproblems recursively.
3. Combine: Combine the solutions of subproblems to get the final solution.
Q.30) Which sorting algorithm is best for sorting small datasets?
● Answer: [A] Insertion sort
● Explanation: Insertion sort is often very efficient for small datasets (e.g., n < 10-20) due
to its low overhead and simple operations. It also performs well on nearly sorted data
(approaching O(n)). Many hybrid sorting algorithms (like Timsort, used in Python)
switch to insertion sort for small partitions.
Q.31) What is the time complexity of selection sort?
● Answer: [A] O(n^2)
● Explanation: Selection sort has a time complexity of O(n^2) in all cases (best, average,
and worst). This is because it always makes n-1 passes, and in each pass 'i', it performs
(n-i) comparisons to find the minimum/maximum element in the remaining unsorted
part.
Q.32) Which of the following is a characteristic of merge sort?
● Answer: [D] Both A and C ([A] It is not an in-place algorithm, [C] It uses a divide and
conquer strategy)
● Explanation:
○ Merge sort is a divide and conquer algorithm.
○ Standard implementations of merge sort are not in-place; they require O(n)
auxiliary space for the merging process.
Q.33) What is the space complexity of merge sort?
● Answer: [A] O(n)
● Explanation: The primary space requirement for merge sort comes from the auxiliary
array used during the merge step, which is proportional to the number of elements 'n'.
The recursive calls also use stack space, which is O(log n). So, the overall space
complexity is dominated by O(n).
Q.34) Which sorting algorithm is best for sorting large datasets that cannot fit into
memory?
● Answer: [A] Merge sort
● Explanation: Merge sort is well-suited for external sorting (sorting data that resides on
disk because it's too large for RAM). Its sequential access pattern during the merge
phase works efficiently with slower disk I/O.
Q.35) What is the average-case time complexity of bubble sort?
● Answer: [A] O(n^2)
● Explanation: The average-case time complexity of bubble sort is O(n^2).
Q.36) Which of the following sorting algorithms is known for being efficient with nearly
sorted data?
● Answer: [A] Insertion sort
● Explanation: Insertion sort exhibits adaptive behavior. If the input array is already
nearly sorted, it performs very efficiently, with a time complexity approaching O(n).
Bubble sort (with an optimization to stop early if no swaps occur in a pass) also benefits
from nearly sorted data.
Q.37) Which sorting algorithm works by comparing elements and swapping them in
place?
● Answer: [B] Insertion sort (This is a general description applicable to many in-place
comparison sorts like Bubble sort, Selection sort, Quick sort, Heap sort as well.)
● Explanation: Many in-place sorting algorithms involve comparing elements and
swapping them to achieve the sorted order. Insertion sort, for example, iterates through
the input elements and, for each element, "inserts" it into its correct position within the
already sorted part of the array by comparing and shifting elements.
Q.38) Which of the following sorting algorithms is not stable?
● Answer: [A] Quick sort
● Explanation: Quicksort, Heap sort, and Selection sort are generally not stable, meaning
they might change the relative order of equal elements. Merge sort, Insertion sort, and
Bubble sort are stable.
Q.39) Which of the following is an in-place sorting algorithm?
● Answer: [D] Insertion sort (also Quick sort (typical implementations), Heap sort, Bubble
sort, Selection sort)
● Explanation: An in-place sorting algorithm is one that sorts the input array using only a
constant amount (O(1)) of additional memory space beyond the space occupied by the
input array itself (though sometimes a small, logarithmic amount of stack space for
recursion is permitted).
○ In-place: Insertion sort, Heap sort, Bubble sort, Selection sort, Quicksort (most
common implementations are in-place, using O(log n) stack space for recursion).
○ Not in-place (typically): Merge sort (uses O(n) auxiliary space).
Q.40) Which sorting algorithm has the worst performance on an already sorted array?
● Answer: [B] Bubble sort (A naive Bubble Sort without optimization will still do O(n^2)
comparisons. A naive Quicksort picking the first/last element as pivot will also degrade
to O(n^2) on sorted data.)
● Explanation:
○ A naive Quicksort (e.g., always picking the first or last element as a pivot) on an
already sorted array will result in O(n^2) performance due to extremely
unbalanced partitions.
○ A standard Bubble Sort will also perform O(n^2) comparisons on a sorted array,
although an optimized version (that stops if no swaps are made in a pass) will
perform in O(n).
○ Insertion Sort performs optimally in O(n) on an already sorted array.
○ Selection Sort will always perform O(n^2) regardless of initial order.
Given the options, and considering common implementations, both Bubble Sort
(unoptimized) and Quicksort (naive pivot) are bad.
Q.41) Which sorting algorithm is faster than selection sort but slower than quicksort?
(Generally, on average for random data)
● Answer: [D] Heap sort
● Explanation:
○ Selection sort: O(n^2)
○ Heap sort: O(n log n) in all cases.
○ Quicksort: O(n log n) on average, but often with better constant factors than Heap
sort, making it faster in practice on average.
Heap sort fits the description of being O(n log n) (faster than O(n^2) Selection
sort) and typically having slightly worse practical performance than an
average-case Quicksort. Merge sort (O(n log n)) could also fit here.
Q.42) Which of the following algorithms is used for sorting numbers that are not in a
fixed range?
● Answer: [B] Radix sort (Can be efficient for integers. [D] Quicksort is a general
comparison sort suitable for any orderable data type without range restrictions.)
● Explanation: Comparison-based sorts like Quicksort, Merge sort, and Heap sort are
general-purpose and work for any data type that can be ordered, without restrictions
on the range of values. Radix sort is specifically designed for integers (or data that can
be mapped to integers) and its efficiency depends on the number of digits (which
relates to the range). Counting sort requires a known, usually small, fixed range. Bucket
sort works well for uniformly distributed data.
Q.43) Which sorting algorithm divides the array into smaller parts and sorts each one
individually?
● Answer: [A] Merge sort (also [C] Quick sort)
● Explanation: This is characteristic of divide-and-conquer algorithms. Both Merge sort
and Quick sort divide the array into smaller parts (subarrays/partitions), recursively sort
these parts, and then (for Merge sort) combine them or (for Quick sort) the array is
sorted once partitions are sorted.
Q.44) Which of the following sorting algorithms uses the concept of a “pivot”?
● Answer: [C] Quick sort
● Explanation: Quicksort is characterized by its use of a "pivot" element. The array is
partitioned around this pivot, with elements smaller than the pivot moved to one side
and elements larger moved to the other.
Q.45) What is the best sorting algorithm for a small dataset with a nearly sorted array?
● Answer: [A] Insertion sort
● Explanation: Insertion sort is highly efficient for small datasets due to its low overhead.
It is also adaptive, meaning its performance improves significantly if the array is already
nearly sorted (approaching O(n) time complexity in such cases).
Q.46) Which sorting algorithm works by dividing the list into sublists of fixed sizes and
then sorting them?
● Answer: [C] Radix sort (This description is not a perfect fit for Radix sort. It's closer to
Bucket Sort if "fixed sizes" refers to ranges for buckets. Radix sort processes digits, not
sublists of fixed element counts in this direct sense.)
● Explanation: This description is somewhat ambiguous.
○ Bucket Sort divides the range of input values into a number of "buckets."
Elements are distributed into these buckets, each bucket is sorted individually
(often using another sort like insertion sort), and then the sorted buckets are
concatenated.
○ Radix Sort sorts integers by grouping keys by individual digits (or parts of keys)
that share the same significant position and value. It doesn't divide the list into
sublists of fixed element counts in the same way.
Given the options, the question might be poorly phrased or intending a specific
interpretation.
Q.47) Which sorting algorithm is best for sorting integers in a fixed range?
● Answer: [A] Counting sort
● Explanation: Counting sort is extremely efficient for sorting integers when the range of
possible key values (k) is not significantly larger than the number of items (n). Its time
complexity is O(n + k). If k is O(n), then counting sort is O(n).
Q.48) Which of the following sorting algorithms works by dividing the array into two
sub-arrays and sorting them independently?
● Answer: [A] Merge sort (also [B] Quick sort)
● Explanation: This describes the "divide" and "conquer" steps of algorithms like Merge
sort and Quick sort. Merge sort explicitly divides into two halves. Quick sort partitions
into two (not necessarily equal) parts around a pivot.
Q.49) Which search algorithm works by progressively halving the search space?
● Answer: [A] Binary search
● Explanation: This is the core principle of binary search, which makes it efficient for
sorted data.
Q.50) Which sorting algorithm is known for being very efficient with large datasets that
have a wide range of values?
● Answer: [B] Radix sort (Can be, for integers. Comparison sorts like Merge/Quick sort
are also good general choices.)
● Explanation: For integer data, Radix sort can be very efficient (linear time complexity
O(d*(n+k)) where d is number of digits, k is base) even with a wide range of values,
provided the number of digits doesn't become excessively large. General-purpose
comparison sorts like Quicksort and Merge sort (O(n log n)) are also robust choices for
large datasets with wide value ranges and work for non-integer data too.