1. What is a Data Structure?

A data structure is a way of organizing, storing, and managing data in a computer so that it can be accessed and modified efficiently.

It defines how data is arranged in memory and how operations such as insertion, deletion, searching, and updating are performed.

Real-World Example:

A library uses a systematic arrangement of books so that a particular book can be found quickly. Similarly, data structures organize data to make operations efficient.

Key Features of Data Structures

  • Efficient Data Organization – Helps store data in a structured way

  • Fast Access – Allows quick retrieval of stored data

  • Modification – Supports insertion, deletion, and updating

  • Problem Solving – Different structures are suitable for different problems

Basic Operations

  • Insertion – Adding new data elements

  • Deletion – Removing existing elements

  • Searching – Finding specific elements

  • Updating – Modifying existing data

  • Traversal – Accessing each element

Examples

  • Array – Elements stored in contiguous memory

  • Linked List – Elements connected using pointers

  • Stack – Follows LIFO

  • Queue – Follows FIFO

  • Tree – Hierarchical structure

  • Graph – Network of connected nodes

Quick View

Whiteboard
Loading diagram...

2. Why do we use Data Structure?

Data Structures are used to organize, store, and manage data efficiently so that operations like searching, insertion, deletion, and updating can be performed effectively.

1. Efficient Data Management

Data structures help store data in a structured way, making it easier to access and modify information.

2. Improves Algorithm Performance

Choosing the right data structure can significantly improve algorithm performance by reducing time complexity and execution time.

3. Faster Operations

Different data structures are optimized for specific operations:

  • Arrays → Fast indexed access

  • Linked Lists → Efficient insertion and deletion

  • Hash Tables → Fast retrieval using keys

  • Trees and Graphs → Represent hierarchical and network relationships

4. Memory Efficiency

Proper data structures help use memory efficiently and avoid unnecessary storage.

5. Handling Large Data

Efficient data structures help applications manage and process large datasets effectively.

6. Foundation of Efficient Software

Applications such as databases, operating systems, search engines, and compilers rely heavily on data structures.

Key Idea:
The right data structure can make an algorithm faster, simpler, and more efficient.

3. What are the Types of Data Structures?

Data structures are broadly classified into two main types:

  1. Linear Data Structures

  2. Non-linear Data Structures

1. Linear Data Structures

In linear data structures, elements are arranged in a sequential order.

Characteristics:

  • Elements are stored in a linear sequence

  • Each element generally has a single predecessor and successor

  • Traversal follows a single path

Examples:

  • Array

  • Linked List

  • Stack

  • Queue

2. Non-linear Data Structures

In non-linear data structures, elements are not arranged sequentially.

They form hierarchical or network relationships.

Characteristics:

  • Elements can have multiple connections

  • Traversal can have multiple paths

  • Useful for hierarchical and network-based relationships

Examples:

  • Tree

  • Graph

Classification

Whiteboard
Loading diagram...

4. What is the Difference Between Linear and Non-linear Data Structures?

The difference lies in how the data elements are organized and connected.

  • Linear → Elements are arranged in a sequence

  • Non-linear → Elements are arranged in a hierarchical or network structure

Linear Data Structures

Elements are arranged one after another.

Examples:

  • Array

  • Linked List

  • Stack

  • Queue

Non-linear Data Structures

Elements can have multiple relationships.

Examples:

  • Tree

  • Graph

Comparison

FeatureLinearNon-linear
ArrangementSequentialHierarchical / Network
RelationshipOne-to-oneOne-to-many / Multiple
TraversalSingle pathMultiple paths
ComplexitySimplerMore complex
ExamplesArray, Linked List, Stack, QueueTree, Graph

Remember:
Linear = One sequence
Non-linear = Multiple relationships

5. What is an Abstract Data Type (ADT)?

An Abstract Data Type (ADT) is a logical or mathematical model that defines what operations can be performed, without specifying how those operations are implemented.

It focuses on the behavior of the data structure rather than its implementation details.

Key Features of ADT

  • Abstraction – Hides implementation details

  • Defined Operations – Specifies available operations

  • Implementation Independent – Can have different implementations

  • Focus on Behavior – Describes what, not how

Examples

  • Stack ADT → push,pop,peek

  • Queue ADT → enqueue,dequeue

  • List ADT → insert,delete,search

ADT vs Data Structure

ADTData Structure
Defines what operations are allowedDefines how operations are implemented
Logical modelPhysical implementation
Implementation independentImplementation specific

Example

A Stack ADT can be implemented using:

  • Array

  • Linked List

Whiteboard
Loading diagram...


6. What is an Algorithm?

An algorithm is a finite set of well-defined steps or instructions used to solve a problem or perform a specific task.

It takes an input, processes it through a sequence of steps, and produces an output.

Key Features

  • Finite – Must complete in a limited number of steps

  • Unambiguous – Each step is clearly defined

  • Input – Accepts zero or more inputs

  • Output – Produces at least one result

  • Effective – Steps must be executable

Common Types of Algorithms

  • Searching – Linear Search, Binary Search

  • Sorting – Bubble Sort, Merge Sort

  • Greedy Algorithms

  • Dynamic Programming

  • Recursion-based Algorithms

Basic Flow

Whiteboard
Loading diagram...


7. Why is Algorithm Analysis Important?

Algorithm analysis helps us evaluate the efficiency of an algorithm in terms of time and space complexity.

It allows us to choose the most suitable solution for a problem.

Key Reasons

1. Performance Evaluation

Helps compare algorithms based on:

  • Time Complexity

  • Space Complexity

2. Optimal Solution Selection

Allows us to choose the most efficient algorithm among multiple solutions.

3. Scalability

Ensures that an algorithm performs well as the input size increases.

4. Efficient Resource Utilization

Helps minimize:

  • Execution time

  • Memory usage

5. Predicting Behavior

Helps understand how an algorithm behaves for different input sizes without necessarily running it.

Key Idea:
Algorithm analysis helps us choose solutions that are faster, scalable, and resource-efficient.

8. What are the Criteria for Analyzing an Algorithm?

Algorithm analysis mainly evaluates its efficiency and performance.

1. Time Complexity

Measures how the running time grows with input size.

Examples:

  • O(n)

  • O(log n)

2. Space Complexity

Measures the amount of memory required by an algorithm.

It includes:

  • Input Space

  • Auxiliary Space

3. Best, Average, and Worst Case

  • Best Case – Minimum time taken

  • Average Case – Expected time for typical inputs

  • Worst Case – Maximum time taken

4. Scalability

Evaluates how well an algorithm performs as the input size increases.

5.Input Constraints

Input constraints help determine whether an algorithm is efficient enough for a given problem.

 Learn more about Input/Output and Constraints Handling in DSA.

Example: Searching

AlgorithmTimeSpace
Linear SearchO(n)O(1)
Binary SearchO(log n)O(1)

9. What is Time Complexity?

Time complexity is a measure of the amount of time an algorithm takes to run as a function of input size (n).

It describes how the running time grows as input size increases, rather than measuring exact execution time in seconds.

Key Concepts

  • Focuses on growth rate

  • Helps compare algorithm efficiency

  • Expressed using Big-O notation

Common Time Complexities

ComplexityName
O(1)Constant
O(log n)Logarithmic
O(n)Linear
O(n log n)Linearithmic
O(n²)Quadratic

Example

Finding an element in an array:

  • Linear Search → O(n)

  • Binary Search → O(log n)

Remember:
Time Complexity tells us how the running time grows, not the exact number of seconds.

For a deeper understanding of algorithm performance, refer to Time and Space Complexity.

10. What is Space Complexity?

Space complexity is the measure of the amount of memory an algorithm uses as a function of input size (n).

It includes both the memory required for the input and the extra memory used during execution.

Components

1. Input Space

Memory required to store the input data.

2. Auxiliary Space

Extra memory used by the algorithm, such as:

  • Variables

  • Recursion stack

  • Temporary storage

  • Extra arrays

Key Concepts

  • Focuses on memory usage

  • Important for memory-constrained systems

  • Often expressed using Big-O notation

Examples

  • Linear Search → O(1) auxiliary space

  • Merge Sort → O(n) auxiliary space

Time Complexity → How much time?
Space Complexity → How much memory?

11. What is Asymptotic Analysis?

Asymptotic analysis is the method of analyzing the time and space complexity of an algorithm as the input size becomes very large.

It focuses on the growth rate of an algorithm while ignoring constant factors and lower-order terms.

Key Concepts

  • Evaluates performance for large input sizes

  • Ignores constants and less significant terms

  • Helps compare algorithms

  • Uses asymptotic notations

Types of Asymptotic Notations

  • Big-O (O) → Upper bound

  • Big-Θ (Θ) → Tight bound

  • Big-Ω (Ω) → Lower bound

Simple View

Whiteboard
Loading diagram...


12. What is Big-O Notation?

Big-O notation is used to describe the growth rate of an algorithm with respect to input size.

It is commonly used to express worst-case complexity and ignores constants and lower-order terms.

Key Concepts

  • Focuses on worst-case performance

  • Describes how performance scales

  • Ignores constants

  • Helps compare algorithm efficiency

Common Big-O Complexities

  • O(1) → Constant

  • O(log n) → Logarithmic

  • O(n) → Linear

  • O(n log n) → Linearithmic

  • O(n²) → Quadratic

Why Does Big-O Matter?

It helps us:

  • Choose efficient algorithms

  • Predict performance for large inputs

  • Compare different algorithms

Interview Tip:
When comparing algorithms, focus on how their complexity grows as n increases.

Important Note: Big-O notation represents an asymptotic upper bound. It is commonly used to express worst-case time complexity, but Big-O and worst case are not the same thing.

13. What is an Array?

An array is a linear data structure that stores a collection of elements of the same data type in contiguous memory locations.

Each element can be accessed using an index.

Key Features

  • Contiguous Memory Allocation

  • Index-based Access

  • Fixed Size

  • Homogeneous Elements

Basic Operations

OperationComplexity
AccessO(1)
InsertionO(n)
DeletionO(n)
TraversalO(n)

Example

Array: [10] [20] [30] [40]
Index:   0    1    2    3

For example:

  • arr[0] → 10

  • arr[2] → 30

Advantages

  • Fast random access

  • Simple to implement

  • Efficient for fixed-size data

Disadvantages

  • Fixed size

  • Insertion and deletion can require shifting

For a deeper understanding of arrays and their operations, read Introduction to Arrays.

14. What are the Types of Arrays?

Arrays can be classified based on their dimensions and structure.

1. One-Dimensional Array

Stores elements in a single linear sequence.

Example:

[10, 20, 30, 40]

Accessed using one index.

2. Two-Dimensional Array

Stores elements in the form of rows and columns.

Example:

[ 1  2  3 ]
[ 4  5  6 ]

Accessed using:

arr[row][column]

3. Multi-Dimensional Array

Arrays with more than two dimensions.

Example:

 arr[x][y][z]

4. Dynamic Array

A dynamic array can resize itself during runtime.

Examples:

  • Python list

  • C++ vector

Quick Comparison

TypeDescriptionIndexing
1DLinear sequenceOne index
2DRows & columnsTwo indices
Multi-dimensionalHigher dimensionsMultiple indices
DynamicResizableOne index

Learn more about One-Dimensional Arrays and how elements are stored and accessed using a single index.

15. What are Multidimensional Arrays?

Multidimensional arrays are arrays that store data in more than one dimension.

They are useful for representing:

  • Tables

  • Matrices

  • Grids

  • Higher-dimensional data

Each element is accessed using multiple indices.

Key Features

  • Store data in multiple dimensions

  • Use more than one index

  • Useful for matrix-like data

  • Can represent complex data structures

1. Two-Dimensional Array

Organized into rows and columns.

[ 1  2  3 ]
[ 4  5  6 ]

Access:

arr[row][column]

2. Three-Dimensional Array

Can be viewed as multiple 2D layers.

Access:

 arr[x][y][z]

Applications

  • Matrices

  • Image processing

  • Game boards

  • Scientific computations

16. What is Dynamic Memory Allocation?

Dynamic memory allocation is the process of allocating and deallocating memory during program execution according to the program's requirements.

  • malloc() – Allocates a block of memory.

  • calloc() – Allocates memory and initializes it to zero.

  • realloc() – Changes the size of previously allocated memory.

  • free() – Releases allocated memory.

Example: In C++, dynamic memory can be allocated using new and released using delete. Containers such as vector manage memory automatically.

17. What is a Linked List?

A linked list is a linear data structure in which elements, called nodes, are connected using pointers instead of being stored in contiguous memory.

Each node contains:

  • Data

  • Reference / Pointer to the next node

Structure of a Node

┌─────────┬─────────┐
│  Data   │  Next   │
└─────────┴─────────┘

Linked List Structure

 [10 | •] → [20|.] -> [30|NULL] 

Key Features

  • Dynamic Size

  • Non-contiguous Memory

  • Efficient insertion and deletion

  • Sequential Access

Types

  • Singly Linked List

  • Doubly Linked List

  • Circular Linked List

Basic Operations

  • Insertion

  • Deletion

  • Traversal

  • Searching

Advantages

  • Efficient insertion and deletion

  • Flexible dynamic size

Disadvantages

  • No random access

  • Extra memory required for pointers

To understand how to visit each node in a linked list, explore Traverse a Linked List.

18. What are the Types of Linked Lists?

Linked lists are classified based on how their nodes are connected and how many pointers each node contains.

1. Singly Linked List

Each node contains data and a pointer to the next node

 [Data | Next] → [Data | Next] → NULL

Features:

  • Traversal is forward only

  • Last node points to NULL

2. Doubly Linked List

Each node contains:

  • Previous pointer

  • Data

  • Next pointer

NULL ← [Prev | Data | Next] ↔ [Prev | Data | Next] → NULL

Features:

  • Traversal is forward and backward

  • Requires extra memory for the previous pointer

3. Circular Linked List

The last node points back to the first node.

 [10] → [20] → [30]
 ↑              │
 └──────────────┘

Features:

  • Forms a loop

  • No NULL at the end

  • Traversal can start from any node

Comparison

TypePointersTraversalEnd Condition
SinglyNextOne directionNULL
DoublyPrev + NextTwo directionsNULL
CircularNextLoopNo NULL

19. What is the Difference Between Array and Linked List?

Both arrays and linked lists are linear data structures, but they differ in how they store and access data.

  • Array → Contiguous memory

  • Linked List → Nodes connected using pointers

Key Differences

FeatureArrayLinked List
MemoryContiguousNon-contiguous
SizeFixedDynamic
AccessDirect / O(1)Sequential / O(n)
InsertionCostlyEfficient
DeletionCostlyEfficient
Memory UsageLessExtra pointer memory
Cache PerformanceBetterPoorer

When to Use?

Use Array when:

  • Fast random access is required

  • Size is relatively fixed

Use Linked List when:

  • Frequent insertions/deletions are required

  • Size is dynamic

Easy Way to Remember:
Array → Fast Access
Linked List → Flexible Size

Important Note: In a linked list, insertion or deletion can take \(O(1)\) time when the required position or node reference is already available. Finding that position may take \(O(n)\) time.

20. What are the Advantages and Disadvantages of Linked Lists?

Advantages of Linked Lists

  • Dynamic size

  • Efficient insertion and deletion when the required position is known

  • Does not require contiguous memory

  • Easy implementation of stacks and queues

Disadvantages:

  • No direct/random access

  • Extra memory required for pointers

  • Sequential traversal is required

21. What is a Stack?

A stack is a linear data structure that follows the LIFO (Last In First Out) principle.

The last element inserted is the first element removed.

Key Features

  • Follows LIFO order
  • Insertion and deletion happen at the top
  • Only one end is accessible

Basic Operations

OperationDescriptionTime
PushAdd element to topO(1)
PopRemove top elementO(1)
Peek / TopView top elementO(1)
isEmptyCheck if stack is emptyO(1)

Example

       ┌────┐
       │ 30 │ ← Top
       ├────┤
       │ 20 │
       ├────┤
       │ 10 │
       └────┘
        LIFO
  Last In → First Out

Implementation

A stack can be implemented using:

  • Array
  • Linked List

Applications

  • Expression evaluation
  • Undo / Redo
  • Function calls
  • Recursion
  • Balanced parentheses

22.How do you Reverse a Singly Linked List?

A singly linked list can be reversed by changing the direction of its pointers so that each node points to its previous node.

Approach:

Use three pointers:

  • prev – Stores the previous node.

  • current – Points to the current node.

  • next – Stores the next node temporarily.

Steps:

  1. Initialize prev = NULL and current = head.

  2. Store the next node in next.

  3. Change current->next to prev.

  4. Move prev and current one step forward.

  5. Repeat until current becomes NULL.

  6. Update the head to prev.

Time Complexity: (O(n))

Space Complexity:(O(1))

Before:10 → 20 → 30 → NULL

After:
30 → 20 → 10 → NULL

23. What Operations can be Performed on Stack?

A stack supports operations that allow elements to be added, removed, and accessed following the LIFO principle.

1. Push

Adds an element to the top of the stack.

Time Complexity: O(1)

2. Pop

Removes the top element.

Time Complexity: O(1)

3. Peek / Top

Returns the top element without removing it.

Time Complexity: O(1)

4. isEmpty

Checks whether the stack is empty.

5. isFull

Checks whether the stack is full.

This is mainly applicable to fixed-size array implementations.

Example

Stack = [10, 20, 30]

  Push(40)
      ↓
[10, 20, 30, 40]

   Pop()
      ↓
[10, 20, 30]

   Peek()
      ↓
     30

Quick View

OperationPurpose
PushAdd element
PopRemove element
PeekView top
isEmptyCheck empty
isFullCheck full

24. What are the Applications of Stack?

Stacks are useful whenever data needs to be processed in a LIFO manner.

1. Function Call Management

The stack maintains the call stack and stores function calls and local variables.

It is especially important for recursion.

2. Expression Evaluation

Stacks are used for:

  • Infix
  • Postfix
  • Prefix

expressions.

3. Parentheses Matching

Stacks help check whether expressions contain balanced parentheses.

4. Undo and Redo

Text editors use stacks to track changes and support undo / redo operations.

5. Backtracking

Used in:

  • Maze solving
  • DFS
  • Puzzles

6. Reversing Data

A stack can be used to reverse strings or sequences.

7. Browser Navigation

Stacks can support back and forward navigation.

Key Idea:
Whenever you need to reverse, backtrack, or process the latest item first, think about a Stack.

25. What is a Queue?

A queue is a linear data structure that follows the FIFO (First In First Out) principle.

The element inserted first is the first element removed.

Key Features

  • Follows FIFO order
  • Insertion happens at the rear
  • Deletion happens from the front
  • Has two ends: front and rear

Basic Operations

  • Enqueue – Add an element at the rear
  • Dequeue – Remove an element from the front
  • Front / Peek – View the front element
  • isEmpty – Check whether queue is empty
  • isFull – Check whether queue is full

Example

 Front                 Rear
  ↓                     ↓
[10] → [20] → [30] → [40]
  ↑
First In              Last In

FIFO → First In First Out

Applications

  • CPU scheduling
  • Printer queue
  • Breadth First Search (BFS)
  • Server request handling

26. Why do we use Queue?

A queue is used when data needs to be processed in a First In First Out (FIFO) manner.

Key Reasons

1. FIFO Processing

Ensures fair and ordered processing.

The first inserted element is handled first.

2. Efficient Operations

  • Enqueue → O(1)
  • Dequeue → O(1)

3. Scheduling and Resource Management

Used in:

  • CPU scheduling
  • Task management

4. Handling Requests

Useful when requests arrive continuously.

Examples:

  • Server requests
  • Printer queues

5. Traversal Algorithms

Queues are used in Breadth First Search (BFS) to process nodes level by level.

Applications

  • Task scheduling
  • Printer management
  • Server requests
  • BFS

Remember:
Queue → FIFO → First In, First Out

27. What is the Difference Between Stack and Queue?

Both Stack and Queue are linear data structures, but they follow different processing orders.

Feature

Stack

Queue

Principle

LIFO

FIFO

Insertion

Top

Rear

Deletion

Top

Front

Operations

Push, Pop

Enqueue, Dequeue

Example

Undo operation

Printer queue

Remember:

Stack → Last In, First Out.

Queue → First In, First Out.

You can also learn how to implement a queue using stacks by exploring Implement Queue Using Stack.

28. What are the Types of Queues?

Queues are classified based on how elements are inserted, removed, and organized.

1. Simple Queue

Follows the standard FIFO principle.

  • Insertion → Rear
  • Deletion → Front

2. Circular Queue

The last position connects back to the first position.

It provides better memory utilization.

3. Priority Queue

Elements are processed based on their priority rather than simply their insertion order.

It can follow:

  • Min-priority
  • Max-priority

4. Deque

A Double-Ended Queue allows insertion and deletion from both ends.

Comparison

TypeInsertionDeletionSpecial Feature
Simple QueueRearFrontFIFO
Circular QueueRearFrontCircular
Priority QueuePriority-basedPriority-basedPriority
DequeFront & RearFront & RearDouble-ended

29. What is a Circular Queue?

A circular queue is a type of queue where the last position is connected back to the first position, forming a circular structure.

It follows FIFO while making better use of available memory.

Key Features

  • Follows FIFO
  • Rear can wrap around to the front
  • Provides better memory utilization
  • Reduces wasted space

Working Principle

When the rear reaches the last index, it can move back to the first index.

This is commonly handled using the modulo operation.

Example

For a queue of size 5:

 [0] [1] [2] [3] [4]  ↑               │
  └───────────────┘

If rear = 4, the next available position can be 0.

Advantages

  • Better memory utilization
  • Reuses empty positions
  • Suitable for fixed-size queues

Disadvantages

  • Slightly more complex
  • Requires careful handling of front and rear

30. What is a Deque (Double-Ended Queue)?

A deque is a linear data structure in which insertion and deletion can be performed from both ends.

Key Features

  • Insertion from front and rear
  • Deletion from front and rear
  • More flexible than a simple queue
  • Can behave like both a stack and queue

Types of Deque

1. Input-Restricted Deque

  • Insertion → One end only
  • Deletion → Both ends

2. Output-Restricted Deque

  • Deletion → One end only
  • Insertion → Both ends

Basic Operations

  • InsertFront
  • InsertRear
  • DeleteFront
  • DeleteRear

Example

       Front              Rear
          ↓                  ↓
       [10] [20] [30] [40]
          ↑                  ↑
       Delete             Delete
       Insert             Insert

Applications

  • Sliding window problems
  • Palindrome checking
  • Undo / Redo
  • Task scheduling

31. What is Recursion?

Recursion is a programming technique in which a function calls itself to solve a problem by breaking it into smaller subproblems.

Key Features

  • A function calls itself
  • Problem is divided into smaller instances
  • Must have a base case
  • Uses the call stack

Components

1. Base Case

The condition where recursion stops.

2. Recursive Case

The part where the function calls itself with a smaller input.

Example: Factorial

 factorial(n)      │
      ├── Base Case: n = 0
      │       ↓
      │       1
      │
      └── Recursive Case
              ↓
       n × factorial(n-1)

For example:

5! = 5 × 4 × 3 × 2 × 1

Advantages

  • Simplifies complex problems
  • Useful in divide and conquer
  • Can make code cleaner

Disadvantages

  • Uses extra call stack memory
  • Can be slower than iteration
  • Risk of stack overflow
To understand recursion through a practical example, try solving the Factorial problem.

32. What is the Difference Between Recursion and Iteration?

Both recursion and iteration can be used to repeat operations, but they work differently.

  • Recursion → Function calls itself
  • Iteration → Uses loops

Key Differences

FeatureRecursionIteration
ApproachFunction calls itselfUses loops
TerminationBase caseLoop condition
MemoryMoreLess
PerformanceFunction-call overheadGenerally faster
CodeOften cleanerMay be longer
RiskStack overflowInfinite loop

Example

Recursion:

fact(n) = n × fact(n-1)

Iteration:

for i = 1 to n
    multiply result by i

When to Use?

Use Recursion when:

  • Problem naturally divides into smaller subproblems
  • Working with trees
  • Using divide and conquer

Use Iteration when:

  • Performance is important
  • Memory usage should be minimized
  • Problem involves simple repetition
For a practical comparison of both approaches, refer to Iteration vs Recursion.

33. What is Linear Search?

Linear search is a simple searching algorithm that checks each element sequentially until the target is found or the list ends.

Key Features

  • Checks elements one by one
  • Works on sorted and unsorted data
  • Simple to implement

Algorithm Steps

  1. Start from the first element
  2. Compare it with the target
  3. If a match is found → return the index
  4. Otherwise move to the next element
  5. Continue until the target is found or the array ends

Example

Array:  [10] [20] [30] [40]
Index:    0    1    2    3
                  ↑
                Target

Target = 30

10 → No
20 → No
30 → Found at index 2

Time Complexity

  • Best Case: O(1)
  • Worst Case: O(n)

Advantages

  • Simple
  • Works on unsorted data
  • Requires no extra memory

Disadvantages

  • Slow for large datasets
  • Less efficient than binary search for sorted data

34. What is Binary Search?

Binary search is an efficient searching algorithm that finds an element in a sorted array by repeatedly dividing the search space in half.

Key Features

  • Works only on sorted data
  • Uses divide and conquer
  • Reduces the search space by half

Algorithm

  1. Find the middle element
  2. If target = middle → Found
  3. If target < middle → Search left half
  4. If target > middle → Search right half
  5. Repeat until found or search space becomes empty

Example

[10] [20] [30] [40] [50]
            ↑
          Middle

Target = 30

The middle element is 30, so the target is found immediately.

Flow

Whiteboard
Loading diagram...

Time Complexity

  • Best Case: O(1)
  • Worst Case: O(log n)

Advantages

  • Much faster for large sorted datasets
  • Efficient searching

Disadvantages

  • Requires sorted data
  • More complex than linear search

35. What is Bubble Sort?

Bubble sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order.

The largest element gradually bubbles up to the end after each pass.

Algorithm Steps

  1. Compare adjacent elements
  2. Swap if they are in the wrong order
  3. Continue through the array
  4. Repeat multiple passes
  5. Stop when no swaps are required

Example

Array:

[5, 3, 2, 4]

Pass 1:

5, 3 → swap → [3, 5, 2, 4]

5, 2 → swap → [3, 2, 5, 4]

5, 4 → swap → [3, 2, 4, 5]

Now 5 is in its correct position.

Visual


[5, 3, 2, 4]
 ↑  ↑
Compare

[3, 5, 2, 4]
    ↑  ↑
   Compare

[3, 2, 5, 4]
       ↑  ↑
      Swap

[3, 2, 4, 5]

Time Complexity

  • Best Case: O(n)
  • Worst Case: O(n²)
"The best case is O(n) when an early-exit flag detects that no swaps were made during a pass."

Advantages

  • Simple to understand
  • Easy to implement
  • In-place

Disadvantages

  • Inefficient for large datasets
  • Performs many comparisons and swaps

36. What is Selection Sort?

Selection sort repeatedly selects the smallest element from the unsorted part and places it at the correct position.

Key Features

  • Divides array into sorted and unsorted parts
  • Selects the minimum element
  • Performs fewer swaps than bubble sort

Algorithm Steps

  1. Assume the first unsorted element is the minimum
  2. Compare it with the remaining elements
  3. Find the actual minimum
  4. Swap it into the correct position
  5. Repeat for the remaining elements

Example

[5, 3, 2, 4]

Pass 1:

Minimum = 2

[2, 3, 5, 4]

Pass 2:

Minimum = 3

[2, 3, 5, 4]

Pass 3:

Minimum = 4

[2, 3, 4, 5]

Time Complexity

  • Best Case: O(n²)
  • Worst Case: O(n²)

Advantages

  • Simple to implement
  • Fewer swaps than bubble sort

Disadvantages

  • Inefficient for large datasets
  • Does not benefit much from already sorted data

37. What is Insertion Sort?

Insertion sort builds the sorted array one element at a time by inserting each element into its correct position.

Key Features

  • Builds a sorted portion gradually
  • Inserts each element into its correct position
  • Works well for small or nearly sorted datasets

Algorithm Steps

  1. Start from the second element
  2. Compare it with previous elements
  3. Shift larger elements to the right
  4. Insert the element at the correct position
  5. Repeat

Example

[5, 3, 2, 4]

Insert 3:

[3, 5, 2, 4]

Insert 2:

[2, 3, 5, 4]

Insert 4:

[2, 3, 4, 5]

Time Complexity

  • Best Case: O(n)
  • Worst Case: O(n²)

Advantages

  • Simple to implement
  • Good for small datasets
  • Efficient for nearly sorted arrays
  • In-place

Disadvantages

  • Inefficient for large datasets
  • Can require many shifts

38. What is Merge Sort?

Merge sort is a divide and conquer sorting algorithm that divides an array into smaller parts, sorts them, and then merges the sorted parts.

Key Features

  • Uses divide and conquer
  • Recursively divides the array
  • Merges sorted subarrays
  • Stable sorting algorithm

Working

Whiteboard
Loading diagram...

Algorithm Steps

  1. Divide the array into two halves
  2. Recursively sort each half
  3. Merge the sorted halves
  4. Continue until the entire array is sorted

Time Complexity

  • Best Case: O(n log n)
  • Worst Case: O(n log n)

Space Complexity

  • O(n) extra space

Advantages

  • Efficient for large datasets
  • Stable
  • Guaranteed O(n log n)

Disadvantages

  • Requires extra memory
  • Not in-place

39. What is Quick Sort?

Quick sort is a divide and conquer sorting algorithm that selects a pivot element and partitions the array around it.

Elements smaller than the pivot go to one side, while larger elements go to the other side.

Key Features

  • Uses divide and conquer
  • Selects a pivot
  • Partitions the array
  • Generally performed in-place

Algorithm Steps

  1. Choose a pivot
  2. Partition the array
  3. Elements smaller than pivot → left
  4. Elements larger than pivot → right
  5. Recursively sort both sides

Example


Array: [5, 3, 2, 4]
Pivot = 5
[3, 2, 4] [5]

Sort left:
[2, 3, 4] [5]

Final:
[2, 3, 4, 5]

Time Complexity

  • Best Case: O(n log n)
  • Average Case: O(n log n)
  • Worst Case: O(n²)

Worst case can occur when the pivot is poorly chosen.

Space Complexity

  • O(log n) recursion stack in the typical balanced case

Advantages

  • Fast in practice
  • Good cache performance
  • Generally in-place

Disadvantages

  • Worst case can be O(n²)
  • Performance depends on pivot selection

40. What is Shell Sort?

Shell sort is an improved version of insertion sort that compares elements that are far apart using a gap sequence.

Key Features

  • Based on insertion sort
  • Uses a gap
  • Compares distant elements
  • Gradually reduces the gap
  • Final gap becomes 1

Algorithm Steps

  1. Choose an initial gap
  2. Compare elements that are gap positions apart
  3. Perform insertion-sort-like operations
  4. Reduce the gap
  5. Repeat until gap = 1

Example

Array: [5, 3, 2, 4]

Gap = 2
   ↓
Compare elements 2 positions apart

Reduce gap
   ↓
Gap = 1

Perform final insertion sort
    ↓
[2, 3, 4, 5]

Time Complexity

  • Best Case: Depends on the gap sequence
  • Worst Case: O(n²)

Advantages

  • Faster than insertion sort for medium-sized datasets
  • Reduces shifts and swaps
  • In-place

Disadvantages

  • Performance depends on the gap sequence
  • Not as efficient as advanced algorithms for large datasets

41. What is a Tree Data Structure?

A tree is a non-linear data structure that organizes data in a hierarchical structure using nodes and edges.

A node can have multiple child nodes.

Key Features

  • Hierarchical structure
  • Consists of nodes and edges
  • Has a root node
  • Nodes can have zero or more children
  • Standard trees contain no cycles

Basic Terminology

  • Root → Topmost node
  • Parent → Node that has children
  • Child → Node derived from another node
  • Leaf Node → Node with no children
  • Subtree → Tree formed from a node and its descendants

Example

Whiteboard
Loading diagram...
  • Root → A
  • Children of A → B, C
  • Leaf Nodes → D, E, C

Types of Trees

  • Binary Tree
  • Binary Search Tree
  • Heap
  • Trie

Applications

  • File systems
  • Database indexing
  • Expression trees
  • Searching and sorting

42. What is a Binary Tree?

A binary tree is a type of tree in which each node can have at most two children.

These are called:

  • Left child
  • Right child

Key Features

  • Maximum two children per node
  • Children are called left and right
  • Hierarchical structure
  • Contains no cycles

Example

Whiteboard
Loading diagram...
  • Root → A
  • Left Child → B
  • Right Child → C
  • Leaf Nodes → D, E, C

Types of Binary Trees

  • Full Binary Tree → Every node has 0 or 2 children
  • Complete Binary Tree → All levels filled except possibly the last
  • Perfect Binary Tree → All levels completely filled
  • Balanced Binary Tree → Height is kept relatively small

Applications

  • Binary Search Trees
  • Heap
  • Expression trees
  • Searching and sorting

43. What is a Binary Search Tree (BST)?

A Binary Search Tree (BST) is a binary tree where each node follows a specific ordering property:

  • Left subtree → Values smaller than the node
  • Right subtree → Values greater than the node

BST Property

For a node with value X:

Whiteboard
Loading diagram...

Example

Whiteboard
Loading diagram...

For node 50:

  • Left → Values < 50
  • Right → Values > 50

Key Features

  • Maximum two children
  • Maintains sorted order
  • Supports searching, insertion, and deletion
  • Standard BSTs generally do not allow duplicate values

Time Complexity

OperationAverageWorst
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)

Worst case occurs when the tree becomes skewed.

Advantages

  • Efficient searching
  • Maintains data in sorted order

Disadvantages

  • Can become unbalanced
  • Worst-case performance becomes O(n)

Important: A BST can become skewed if elements are inserted in an unfavourable order. In that case, searching, insertion and deletion can take (O(n)) time.

44. What is Tree Traversal?

Tree traversal is the process of visiting all nodes of a tree in a specific order.

Tree traversal is mainly divided into:

  1. Depth First Traversal (DFS)
  2. Breadth First Traversal (BFS)

Depth First Traversal

DFS explores nodes deep into the tree before backtracking.

It includes:

  • Inorder → Left → Root → Right
  • Preorder → Root → Left → Right
  • Postorder → Left → Right → Root

Breadth First Traversal

Also called Level Order Traversal.

It visits nodes level by level and uses a queue.

Example

Whiteboard
Loading diagram...
TraversalOrder
InorderD, B, E, A, C
PreorderA, B, D, E, C
PostorderD, E, B, C, A
Level OrderA, B, C, D, E

Applications

  • Searching tree nodes
  • Expression evaluation
  • File system traversal
  • Tree-based algorithms

45. What are the Types of Tree Traversals?

Tree traversal methods determine the order in which nodes are visited.

They are mainly classified into:

  • Depth First Traversal (DFS)
  • Breadth First Traversal (BFS)

1. Inorder Traversal

Left → Root → Right

In a BST, inorder traversal produces elements in sorted order.

2. Preorder Traversal

Root → Left → Right

The root is visited first.

Useful for copying trees.

3. Postorder Traversal

Left → Right → Root

The root is visited last.

Useful for deleting trees.

4. Level Order Traversal

Visits nodes level by level.

It uses a queue.

Example

Whiteboard
Loading diagram...
  • Inorder → D, B, E, A, C
  • Preorder → A, B, D, E, C
  • Postorder → D, E, B, C, A
  • Level Order → A, B, C, D, E

Quick Memory Trick

Inorder   → L N R
Preorder  → N L R
Postorder → L R N

N = Node / Root

46. What is a Graph?

A graph is a non-linear data structure consisting of a set of vertices (nodes) and edges that connect pairs of vertices.

Graphs are commonly used to represent relationships between entities.

Key Features

  • Contains vertices and edges
  • Represents complex relationships
  • Edges can be directed or undirected
  • Graphs can be weighted or unweighted

Types of Graphs

1. Directed Graph

Edges have a direction.

A → B

2. Undirected Graph

Edges have no direction.

A — B

3. Weighted Graph

Edges have associated weights, such as cost or distance.

4. Unweighted Graph

Edges have no weights.

Example

Whiteboard
Loading diagram...

Vertices:

A, B, C

Edges:

A-B, B-C, A-C

Applications

  • Social networks
  • Navigation systems
  • Network routing
  • Recommendation systems

47. What is Depth First Search (DFS)?

Depth First Search (DFS) is a graph traversal algorithm that explores as far as possible along a branch before backtracking.

Key Features

  • Traverses deep first
  • Uses recursion or a stack
  • Works with graphs and trees
  • Does not necessarily find the shortest path

Algorithm Steps

  1. Start from a source node
  2. Mark it as visited
  3. Visit an unvisited neighbor
  4. Continue deeper
  5. Backtrack when no unvisited neighbor remains

Example

Whiteboard
Loading diagram...

DFS starting from A can be:

A → B → C → D

Working Idea

Whiteboard
Loading diagram...

Time Complexity

O(V + E)

Where:

  • V = Number of vertices
  • E = Number of edges

Applications

  • Path finding
  • Cycle detection
  • Topological sorting
  • Connected components

Advantages

  • Simple to implement
  • Can use less memory than BFS in some cases

Disadvantages

  • Does not guarantee the shortest path
  • Can explore deep unnecessary paths

48. What is Breadth First Search (BFS)?

Breadth First Search (BFS) is a graph traversal algorithm that visits nodes level by level.

It explores all neighbors of a node before moving to the next level.

Key Features

  • Traverses level by level
  • Uses a queue
  • Finds the shortest path in unweighted graphs
  • Works with graphs and trees

Algorithm Steps

  1. Start from a source node
  2. Mark it as visited
  3. Enqueue the node
  4. Dequeue a node
  5. Enqueue its unvisited neighbors
  6. Repeat until the queue becomes empty

Example

Whiteboard
Loading diagram...

BFS starting from A:

A → B → D → C

Working Idea

Level 1 → A 
Level 2 → B, D 
Level 3 → C

Time Complexity

O(V + E)

Where:

  • V = Vertices
  • E = Edges

Applications

  • Shortest path in unweighted graphs
  • Level order traversal
  • Network broadcasting
  • Connected components

Advantages

  • Finds shortest path in unweighted graphs
  • Systematic level-wise traversal

Disadvantages

  • Requires more memory for the queue
  • Can be less efficient than DFS in some situations

49. What is Hashing?

Hashing is a technique used to map data or keys to a fixed-size value (index) using a hash function.

It enables fast operations such as searching, insertion, and deletion.

Key Features

  • Uses a hash function
  • Provides fast data access
  • Stores data in a hash table
  • Average operation time is O(1)

Hash Function

A hash function takes a key and produces an index.

Example:

h(key) = key % table_size

Example

For:

key = 25
table_size = 10
h(25) = 25 % 10 = 5

So the key maps to index 5.

Collision

When two keys map to the same index, a collision occurs.

Collision Handling

1. Chaining

Multiple elements are stored at the same index using a list.

2. Open Addressing

Another empty slot is searched.

Advantages

  • Fast search, insertion, and deletion
  • Average complexity O(1)
  • Efficient for large datasets

Disadvantages

  • Collisions can occur
  • Performance depends on the hash function
  • May require extra memory

Applications

  • Hash Maps
  • Dictionaries
  • Database indexing
  • Caching
  • Password storage
To learn more about sets and their operations, explore Introduction to Set.

50. What is a Hash Table?

A hash table is a data structure that stores data in key-value pairs.

A hash function is used to calculate an index where the value should be stored.

Key Features

  • Stores key-value pairs
  • Uses a hash function
  • Provides average O(1) access
  • Efficient for searching, insertion, and deletion

How Does a Hash Table Work?

Whiteboard
Loading diagram...


Example

Suppose:

Key = 25
Value = "Apple"

Hash function:

h(25) = 25 % 10 = 5

The value can be stored at index 5.

Index     Value
0
1
2
3
4
5 25 → Apple
6
7
8
9

Collision

A collision occurs when multiple keys map to the same index.

Collision Handling

  • Chaining → Store multiple elements in a linked list
  • Open Addressing → Find another available slot

Time Complexity

OperationAverage CaseWorst Case
SearchO(1)O(n)
InsertionO(1)O(n)
DeletionO(1)O(n)

Advantages

  • Very fast data retrieval
  • Efficient for large datasets
  • Useful for key-based access

Disadvantages

  • Collisions can reduce performance
  • Requires a good hash function
  • May use extra memory

Applications

  • Dictionaries / Maps
  • Database indexing
  • Caching systems
  • Symbol tables in compilers
Final Memory Trick:
Hashing = Technique
Hash Table = Data Structure
Hash Function = Key → Index

Practice Problems

Practice the following problems to strengthen your understanding of data structures and algorithms.

  1. Reverse an Array: Reverse Array

  2. Check Whether an Array is Sorted: Check if Array is Sorted

  3. Valid Parentheses: Solve Valid Parentheses

  4. Number of Islands: Solve Number of Islands

For more coding practice, visit ExamAdda Practice.

How to Answer Data Structure Questions in an Interview

  • Start with a definition: Explain what the data structure or algorithm does.

  • Mention time complexity: Explain the complexity of its main operations.

  • Explain the use case: Describe when and why it is useful.

  • Expect follow-up questions: Interviewers may ask about advantages, disadvantages and comparisons.

  • Draw before coding: Use diagrams to understand pointers, linked lists, trees and graphs.

Common Mistakes Freshers Make

Mistake

Correct Understanding

Big-O always means worst case

Big-O represents an upper bound.

Linked list insertion is always O(1)

Finding the insertion position may take O(n).

Bubble Sort best case is always O(n)

Requires an early-exit optimization.

Quick Sort is always O(n log n)

Worst case is O(n²).

Hash table lookup is always O(1)

Average O(1), worst case O(n).

Conclusion

Understanding data structures is essential for solving programming problems and performing well in technical interviews.

Once you are comfortable with these 50 questions, continue your preparation with Intermediate Data Structure Interview Questions and practise mock interviews through the ExamAdda Interview Hub.