Data Structures and Algorithms Tutorial 5 of 486
Foundations 17/41
Fundamentals
- Conditional Statements in DSA
- For Loop
- While Loop
- Functions
- Classes and Objects in DSA
- Order of Growth
- Asymptotic Analysis
- Big-O Notation
- Theta Notation
- Big-Omega Notation
- Time Complexity
- Space Complexity
- Input and Output
Maths, Pattern & Recursion
- Recursion
- Analysis of Recursion
- Even or Odd
- Sum of Natural Numbers
- Closest Number
- Sum of Consecutive Numbers
- Solid Rectangle
- Floyd's Triangle
- Hollow Rectangle
- Print 1 to N
- Print N to 1
- Factorial
- GCD
- Power
- Pyramid
- Hollow Diamond
- Count Digits
- Prime Testing
- Armstrong Number
- Trailing Zeros
- Prime Factors
- All Divisors
- Butterfly Pattern
- Palindrome Number
- Tower of Hanoi
- Non-Attacking Knights
- Josephus Problem
- Water Jug Problem
Core Data Structures 0/224
Array & String
- Array Basics
- String Basics
- Matrix Basics
- Is Sorted
- Multiply with Adjacent
- Reverse Array
- Reverse in Groups
- Rotate Array
- Generate All Subarrays
- Arrange by Sign
- Stock Buy/Sell - One Transaction
- Stock Buy/Sell - Multiple Transactions
- Leaders in Array
- Same Strings
- Palindrome String
- Toggle Case
- Remove Occurrences
- Remove Spaces
- Check Subsequence
- First Non-Repeating Character
- Pangram
- Majority Element
- Majority Element II
- Sorted Subsequence of 3
- Count Strictly Increasing Subarrays
- Next Permutation
- Kadane's Algorithm
- Sum of All Subarrays
- Maximum Product Subarray
- Implement atoi
- URLify
- Multiply Large Numbers
- Diagonal Traversal
- Magic Square
- Boundary Traversal
- Spiral Matrix
- Toeplitz Matrix
- Matrix Zig-Zag
- Transpose of Matrix
- Rotate Matrix by 90 Degrees
- Conway's Game of Life
- Queries in a Matrix
- Set Matrix Zeroes
- Maximum Circular Subarray Sum
- Next Smallest Palindrome
- Lexicographic Rank
- Text Justification
Linked List
- Linked List Basics
- Singly Linked List
- Doubly Linked List
- Circular Linked List
- Reverse Singly Linked List
- Reverse Doubly Linked List
- Reverse in Groups
- Reorder List
- Find Middle
- Remove Nth From End
- Check Palindrome
- Detect Cycle
- Intersection of Y-Shaped Lists
- Sort 0s 1s 2s
- Add Two Numbers
- Merge K Sorted Lists
- Browser History
- Twitter Design
- LRU Cache
- LFU Cache
- Flatten Linked List
- Clone Linked List With Random Pointer
Stack
- Stack Basics
- Reverse Stack
- Sort Stack
- Balanced Parentheses
- Postfix Evaluation
- Infix Evaluation
- Infix to Postfix
- Redundant Brackets
- Longest Valid Parentheses
- Stack Using Queues
- Two Stacks in an Array
- K Stacks in an Array
- Stack With getMin
- Remove K Digits
- Next Greater Element
- Stock Span Problem
- Previous Smaller Element
- Largest Rectangle in Histogram
- Trapping Rain Water
- Decode String
Queue
- Queue Basics
- Circular Queue
- Queue Using Stacks
- FIFO Page Replacement
- Reverse a Queue
- Reverse First K Elements
- Interleave Queue
- K Queues in an Array
- First Non-Repeating Character in a Stream
- Minimum Knight Steps
Deque
- Deque Basics
- Circular Array Implementation
- Lexicographically Largest Permutation
- Generate Bitonic Sequence
- Sliding Window Maximum
- Longest Subarray With Difference <= X
- Minimum Deques to Sort Array
Hashing
- Hashing Basics
- Linear Probing
- Separate Chaining
- Quadratic Probing
- Distinct in Array
- Is Subset
- Union of Arrays
- Intersection of Arrays
- Two Sum
- Fizz Buzz
- Pair Sums Divisible by K
- Roman to Integer
- Isomorphic Strings
- Count Frequencies
- Most Frequent Element
- Maximum Subsets
- Anagrams
- Longest Consecutive Subsequence
- Consecutive Subsequence
Heap
- Heap Basics
- Check for Heap
- Heap Sort
- Kth Largest
- K Largest Elements
- Height of Heap
- Connect N Ropes
- Nearly Sorted Array
- BST to Min Heap
- K Max Sum Combinations
- Median in a Stream
- Kth Largest in a Stream
- Merge K Sorted Arrays/Lists
- Range Covering K Sorted Lists
- Skyline Problem
- Sort by Frequency
Binary Tree
- Binary Tree Basics
- Inorder Traversal
- Preorder Traversal
- Postorder Traversal
- Level Order Traversal
- Size of Tree
- Depth of Tree
- Maximum Width
- Check Balanced Tree
- Identical Trees
- Mirror Tree
- Sum Tree
- Left View
- Right View
- Path Sum
- Maximum Path Sum
- Serialize and Deserialize
- Iterative Inorder
- Iterative Preorder
- Iterative Postorder
- Morris Inorder
- Diameter of Tree
- Boundary Traversal
- Tree From Preorder and Inorder
- Connect Nodes at Same Level
- Invert Tree
- Flatten Tree
- Vertical Traversal
- Bottom View
- Top View
- Spiral Level Order
- Lowest Common Ancestor
- Distance K
- Subtree Check
Binary Search Tree
- BST Basics
- Search in BST
- Insert in BST
- Delete in BST
- Ceil in BST
- Floor in BST
- Predecessor and Successor
- Kth Smallest Element
- Two Sum in BST
- Sorted Array to BST
- Merge Two BSTs
- Validate BST
- Lowest Common Ancestor
- Recover BST
- Largest BST Subtree
Trie
- Implement Trie
- Longest Word With All Prefixes
- Count Distinct Substrings
- Maximum XOR of Two Numbers
- Maximum XOR Queries
- Pairs With XOR Less Than K
- Search Suggestions System
- Palindrome Pairs
Graph
- Graph Representation
- BFS Traversal
- DFS Traversal
- Flood Fill
- Number of Islands
- Connected Components in Undirected Graph
- Cycle in Undirected Graph
- Cycle in Directed Graph
- Bipartite Graph
- Rotten Oranges
- Topological Sort
- Course Schedule I
- Course Schedule II
- Alien Dictionary
- Dijkstra's Algorithm
- Floyd Warshall
- Bellman-Ford
- Minimum Cost Path
- Shortest Cycle in Undirected Graph
- Distance of Nearest 1
- Word Ladder
- Prim's Algorithm
- Disjoint Set Union
- Kruskal's Algorithm
- Detect Cycle Using DSU
- Number of Connected Components
Problem-Solving Patterns 0/99
Two-Pointer
- Two-Pointer Technique
- Two Sum in Sorted Array
- Smallest Subarray
- Unique Elements
- Sentence Palindrome
- Three Sum
- Celebrity Problem
- Closest Pair from Two Arrays
- Container With Most Water
- Common Elements in Three Arrays
- Reverse Words
- Four Sum
- Closest Triplet
- Count Triplets
Sliding Window
- Sliding Window Technique
- Maximum Sum Subarray of Size K
- Maximum XOR of K Size
- Distinct in Every Window
- MEX of Subarrays
- Minimum Swaps to Group All 1s
- First Negative in Every Window
- Chocolate Distribution
- Maximize Ones
- Equal Substring With Cost <= K
- Fruit Into Baskets
- Subarray With Given Sum
- Smallest Subarray With Sum Greater Than X
- Minimum Window Subsequence
- Minimum Window Substring
- Subarrays With K Odds
- Subarrays Less Than K
- Longest Substring With Distinct Characters
- Longest Substring With K Unique Characters
- Count Anagrams
Prefix Sum
- Prefix Sum Basics
- Prefix Sum Array
- 2D Prefix Sum
- Range Queries
- Equilibrium Index
- Product of Array Except Self
- Difference Array
- 2D Difference Array
- Subarray With Zero Sum
- Largest Subarray With Zero Sum
- Largest Subarray With Equal 0s and 1s
- Longest Subarray With Sum K
- Count Subarrays With Sum K
- Count Subarrays With Given XOR
Bit Manipulation
- Bit Manipulation Basics
- Swap Without Third Variable
- Kth Set Bit
- Only Set Bit
- Power of Two
- Sort by Set Bits
- Power of Four
- Binary Palindrome
- Rotate Bits
- Swap Odd and Even Bits
- Count Set Bits
- Count Total Set Bits
- Maximum Consecutive 1s
- Missing Number
- One Odd Occurring
- Two Odd Occurring
- Missing and Repeating
- Unique Numbers II
- Gray Codes
- Hamming Distance
- Sum of Pair XORs
- Sum of Subset XORs
- Subarray XORs
- Subsets
- Subsequences
Backtracking
- Backtracking Basics
- Permutations
- Rat in a Maze
- Word Search
- N-Queen Problem
- Sudoku Solver
- Word Break
- Knight's Tour
- Palindromic Partitions
- M-Coloring
Greedy
- Greedy Algorithm Basics
- Fractional Knapsack
- Assign Cookies
- Smallest Subset With Greater Sum
- Minimum Notes With Given Sum
- Activity Selection
- Huffman Coding
- Jump Game
- Job Sequencing
- Non-Overlapping Intervals
- Gas Station
- Stable Marriage
- Minimize Maximum Height Difference
- No Two Adjacent Same
- Minimize Cash Flow
- Min Time to Finish Jobs With Constraints
Core Algorithms 0/122
Searching
- Searching Basics
- Largest Element
- Second Largest
- Local Min and Max
- Search Insert Position
- Lower Bound
- Upper Bound
- Single Element in Sorted Array
- Missing Natural Number
- Count Occurrences
- Search in 2D Matrix
- Search in Sorted and Rotated Array
- Search in Sorted and Rotated Array II
- K Closest Elements
- Search in Almost Sorted Array
- Peak Element
- Peak Element in 2D
- Range Based Counts
- Kth Missing Positive
- Search in Row-Column Sorted Matrix
- Square Root
- Nth Root
- Check Power
- Book Allocation
- Koko Eating Bananas
- Aggressive Cows
- Median in Row Sorted Matrix
- Kth Smallest in Row and Column Sorted Matrix
- M Bouquets
- Kth in Multiplication Table
- Median of Two Sorted Arrays
- Kth Element of Two Sorted Arrays
Sorting
- Sorting Basics
- Wave Form
- Sort by Length
- Minimum Difference Pair
- Merge Overlapping Intervals
- Form Largest Number
- Meeting Rooms
- Insert and Merge Intervals
- Minimize Moves
- Quick Sort
- Sort Binary Array
- Move Zeroes to End
- Sort Ternary Array
- Merge Sort
- Union of Two Sorted Arrays
- Intersection of Two Sorted Arrays
- Merge Without Extra Space
- Minimum Platforms
- Inversion Count
- Cycle Sort
- Minimum Missing Positive
- Minimum Swaps to Sort
Dynamic Programming
- Dynamic Programming Basics
- Climbing Stairs
- Count Without Consecutive 1s
- Frog Jump
- House Robber
- Maximum Segments
- Coin Change
- Decode Ways
- Word Break
- Unique Paths
- Minimum Cost Path
- Longest Common Subsequence
- Edit Distance
- Distinct Subsequences
- Largest Square Submatrix of 1s
- Partition Equal Subset Sum
- Subset Sum
- Count Subsets With Given Sum
- Target Sum
- 0/1 Knapsack
- Coin Change II
- Rod Cutting
- Unique Paths in a Grid
- Maximum Path Sum in Matrix
- Longest Increasing Path
- Longest Common Substring
- Shortest Common Supersequence
- Interleaving String
- Wildcard Matching
- Longest Palindromic Substring
- Buy/Sell With Cooldown
- Buy/Sell With At Most Two Transactions
- Buy/Sell With K Transactions
- Buy/Sell With Transaction Fee
- Longest Increasing Subsequence
- Number of LIS
- Longest Bitonic Subsequence
- Longest String Chain
- Matrix Chain Multiplication
- Minimum Cost to Cut a Stick
- Palindrome Partitioning
- Boolean Parenthesization
- Partition Array for Maximum Sum
- Egg Dropping
String Matching
- Substring Search
- Rabin-Karp
- KMP Algorithm
- Z Algorithm
- Longest Prefix Suffix
- Manacher's Algorithm
- Longest Palindromic Substring
- Palindrome Substring Queries
- Minimum Repeats for Substring
Number Theory
- nCr
- Euler's Totient
- Sieve of Eratosthenes
- Pascal's Triangle
- Modular Exponentiation
- Segmented Sieve
Range Query
- Segment Tree
- Min-Max Range Queries
- Range LCM Queries
- Range XOR Queries
- Lazy Propagation
- Flipping Sign
- Segment Tree on N-ary Rooted Tree
- Fenwick Tree
- Sum and Update Queries on 3D Matrix
Classes and Objects in DSA
Learn how classes and objects represent data and behavior in DSA, providing a foundation for implementing custom data structures and algorithms.
On this page
Classes and Objects in DSA
Classes and objects provide a way to represent data and related operations together.
In DSA, they are commonly used to represent custom data structures such as:
- Linked-list nodes
- Tree nodes
- Graph vertices
- Linked-list structures
- Stack and queue implementations
- Custom data structures
For example, a linked-list node can contain:
Data
Next
A class can represent this structure:
class Node
data
next
An object is an actual instance of that class.
1. What Is a Class?
A class is a blueprint that defines the data and behavior of an object.
For a linked-list node, we might define:
class Node
data
next
The class describes what every node should contain.
Conceptually:
Node
├── data
└── next
2. What Is an Object?
An object is an instance created from a class.
For example:
Node first
creates a node object.
The object can contain:
data = 10
next = null
Another object can contain:
data = 20
next = null
Both objects follow the structure defined by the Node class.
3. Class vs Object
| Class | Object |
|---|---|
| Blueprint | Instance |
| Defines structure | Contains actual values |
| Describes what an object has | Represents an actual entity |
Example: Node |
Example: new Node(10) |
A simple way to remember:
Class → Blueprint
Object → Actual instance
4. Classes in Linked Lists
Classes are commonly used to represent linked-list nodes.
Conceptually:
class Node
data
next
A linked list can then be represented as:
10 → 20 → 30 → null
Each value is stored inside a node object.
The structure is:
Node Node Node
┌──────┐ ┌──────┐ ┌──────┐
│ 10 │ → │ 20 │ → │ 30 │ → null
└──────┘ └──────┘ └──────┘
The next reference connects one object to another.
5. Classes in Trees
Classes are also useful for representing tree nodes.
A binary tree node can contain:
data
left
right
Conceptually:
class TreeNode
data
left
right
A tree such as:
10
/ \
5 15
can be represented using three node objects.
Each object stores its value and references to its child nodes.
6. Classes in Graphs
Graphs can also be represented using classes.
For example, a vertex may contain:
class Vertex
value
neighbors
The neighbors collection stores references to connected vertices.
Conceptually:
A ─── B
│ │
└── C ┘
Each vertex can be represented as an object.
7. Data and Behavior
A class can contain both:
Data
and:
Behavior
For example, a stack class may conceptually contain:
class Stack
data
push()
pop()
peek()
The data represents the state of the stack.
The methods represent operations that can be performed on it.
This makes classes useful when implementing complete data structures.
8. Classes for Custom Data Structures
Classes become particularly useful when a data structure requires multiple related pieces of information.
For example, a linked list may have:
LinkedList
├── head
├── insert()
├── delete()
└── search()
A node may have:
Node
├── data
└── next
This separates the data structure representation from the operations performed on it.
9. Why Classes Are Useful in DSA
Classes help us:
- Represent complex data
- Group related values
- Connect objects together
- Build custom data structures
- Organize operations
- Make implementations easier to understand
For example:
Linked List
|
+── Node
| ├── data
| └── next
|
+── insert()
+── delete()
+── search()
This provides a structured way to implement the data structure.
10. Object References
In many DSA implementations, objects can contain references to other objects.
For example:
Node A
|
↓
Node B
|
↓
Node C
The nodes are separate objects, but references connect them.
This concept is fundamental to:
- Linked lists
- Trees
- Graphs
For example:
Node
├── data
└── next → another Node
The next reference allows nodes to form a chain.
11. Classes and DSA Algorithms
Algorithms operate on the objects created from these classes.
For example, a linked-list traversal may work conceptually as:
current = head
while current != null
process current.data
current = current.next
Here:
Nodedefines the structure.- Objects represent individual nodes.
nextconnects the nodes.- The algorithm traverses those objects.
Therefore, understanding classes and objects helps when implementing DSA algorithms in object-oriented languages.
12. Classes vs Built-in Data Types
Simple problems can often use built-in types:
int
string
array
But more complex data structures may require custom structures.
For example, a tree node needs:
value
left
right
A custom class can represent all three together:
TreeNode
├── value
├── left
└── right
This makes the structure easier to represent and manipulate.
13. Complexity Considerations
Creating a simple object generally takes constant time and space:
Time: O(1)
Space: O(1)
However, the overall complexity depends on how many objects are created and how they are used.
For example, creating n linked-list nodes requires approximately:
Space: O(n)
The class itself does not determine the algorithm's complexity.
The operations performed on the objects determine the complexity.
14. Common DSA Examples
Classes and objects are commonly encountered when implementing:
Linked List
Node
├── data
└── next
Binary Tree
TreeNode
├── data
├── left
└── right
Graph
Vertex
├── data
└── neighbors
Stack
Stack
├── data
├── push()
└── pop()
Queue
Queue
├── data
├── enqueue()
└── dequeue()
Common Mistakes
Confusing a class with an object
Remember:
Class → blueprint
Object → instance
Mixing node data and structure
For a linked-list node:
data
next
data stores the value, while next represents the connection to another node.
Creating unnecessary structures
Not every DSA problem requires a custom class.
Use a custom class when the problem needs a structure that cannot be represented clearly using simpler data types.
Quick Reference
| Concept | Meaning |
|---|---|
| Class | Blueprint for objects |
| Object | Instance of a class |
| Property | Data stored by an object |
| Method | Operation associated with an object |
| Reference | Connection to another object |
| Node | Common object used in data structures |
Key Takeaways
- A class defines the structure and behavior of objects.
- An object is an instance of a class.
- Classes are useful for representing custom data structures.
- Linked-list nodes commonly use
dataandnext. - Tree nodes commonly use
data,left, andright. - Graph vertices can contain values and references to neighbors.
- Objects can be connected using references.
- Classes help organize both data and operations.
- Creating a simple object is generally
O(1)time and space. - The overall complexity depends on how objects are created and processed.
Practice Questions
- What is the difference between a class and an object?
- Design a
Nodeclass for a singly linked list. - Design a
TreeNodeclass for a binary tree. - What properties are required for a doubly linked-list node?
- How can objects be connected to represent a linked list?
- Design a basic class for a stack.
- Design a basic class for a queue.
- Explain how objects can represent vertices in a graph.
- What is the space complexity of creating
nnode objects? - Identify when a custom class is useful in a DSA problem.
What's Next?
Classes and objects provide the building blocks for representing custom data structures.
The next lessons can use these concepts to represent structures such as linked lists, trees, graphs, stacks, and queues.
Related
-
Java Constructors
Learn Java constructors, including default and parameterized constructors, constructor overloading, chaining, and how constructors initialize objects.
-
Java Encapsulation
Learn Java encapsulation, how to protect object data using access modifiers, getters and setters, and why encapsulation improves code security and maintainability.
-
Inheritance
Learn Java inheritance, including single, multilevel, and hierarchical inheritance, method overriding, super, and how inheritance supports code reuse and polymorphism.
-
Even or Odd
Learn how to determine whether an integer is even or odd using the modulo operator and understand the logic behind this basic DSA problem.