Data Structures and Algorithms Tutorial 2 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
For Loop
Learn how for loops help DSA algorithms repeat operations, traverse data, control iterations, and solve problems with predictable time complexity.
On this page
- 1. Basic Structure
- 2. How a for Loop Executes
- Pattern 1: Traverse
- Pattern 2: Count
- Pattern 3: Accumulate
- Pattern 4: Find Maximum
- Pattern 5: Search
- Off-by-One Errors
- Starting From the Wrong Index
- Wrong Loop Direction
- Infinite Loops
- 1. How many times does it execute?
- 2. What happens inside the loop?
- 3. Are there multiple or nested loops?
For Loop
A for loop is a control structure used to repeat an operation a known number of times.
In DSA, for loops are commonly used to:
- Traverse arrays
- Process strings
- Examine every element
- Perform repeated calculations
- Compare elements
- Count values
- Build algorithmic solutions
A simple DSA pattern is:
for each element
process the element
For example, to process every element of an array:
for i = 0 to n - 1
process arr[i]
The loop runs once for each valid index.
1. Basic Structure
The general structure of a for loop is:
for initialization; condition; update
operation
For example:
for i = 0; i < 5; i++
print i
The loop produces:
0
1
2
3
4
The three important parts are:
| Part | Purpose |
|---|---|
| Initialization | Sets the starting value |
| Condition | Determines whether another iteration should run |
| Update | Changes the loop variable |
2. How a for Loop Executes
Consider:
for i = 0; i < 5; i++
process i
The execution is:
i = 0
↓
0 < 5 → true
↓
process 0
↓
i++
↓
i = 1
↓
1 < 5 → true
↓
process 1
↓
...
↓
i = 5
↓
5 < 5 → false
↓
Stop
The condition is checked before every iteration.
3. for Loop for Array Traversal
One of the most common uses of a for loop in DSA is traversing an array.
Given:
arr = [10, 20, 30, 40, 50]
We can process every element using:
for i = 0; i < n; i++
process arr[i]
The indexes are:
0 → 10
1 → 20
2 → 30
3 → 40
4 → 50
The loop visits every element exactly once.
This is the foundation of many array algorithms.
4. Traversing an Array
A typical pattern is:
for i = 0; i < arr.length; i++
process arr[i]
For example:
arr = [4, 7, 2, 9, 5]
for i = 0 to arr.length - 1
print arr[i]
Output:
4
7
2
9
5
This pattern is so common in DSA that it is worth recognizing immediately.
5. Counting Elements
A for loop can be combined with a condition to count elements.
For example, count positive numbers:
count = 0
for each element
if element > 0
count++
For:
[-2, 5, 7, -1, 3]
the result is:
count = 3
This gives us a common DSA pattern:
Traversal
↓
Condition
↓
Update result
6. Finding Maximum Using a for Loop
A for loop can be used to find the maximum element.
Given:
[7, 3, 12, 5, 9]
Algorithm:
max = arr[0]
for i = 1 to n - 1
if arr[i] > max
max = arr[i]
return max
The loop checks every remaining element.
The condition:
arr[i] > max
determines whether the current maximum needs to be updated.
The final result is:
12
7. Finding Minimum Using a for Loop
The same pattern can find the minimum.
min = arr[0]
for i = 1 to n - 1
if arr[i] < min
min = arr[i]
return min
The key difference is the comparison:
arr[i] < min
This demonstrates how a loop and a conditional statement work together to solve a DSA problem.
8. Calculating a Sum
A for loop can process every element and maintain a running sum.
sum = 0
for each element
sum = sum + element
return sum
For:
[2, 4, 6, 8]
the calculation is:
sum = 0
sum = 0 + 2
sum = 2 + 4
sum = 6 + 6
sum = 12 + 8
Final result:
20
9. Looping Through a String
A string can also be processed character by character.
For:
"hello"
we can use:
for i = 0 to length - 1
process string[i]
The loop visits:
h
e
l
l
o
This pattern is commonly used in DSA problems involving strings.
10. Reverse Traversal
A for loop does not always have to move from left to right.
We can traverse an array backwards.
for i = n - 1; i >= 0; i--
process arr[i]
For:
[10, 20, 30, 40]
the traversal order becomes:
40
30
20
10
Reverse traversal is useful in many algorithmic problems.
11. Custom Step Size
The update operation does not always have to be i++.
For example:
for i = 0; i < n; i += 2
process arr[i]
This visits:
0
2
4
6
...
Similarly:
for i = 10; i >= 0; i -= 2
process i
The loop can move in different directions or increments depending on the algorithm.
12. Nested for Loops
A for loop can contain another for loop.
This is called a nested loop.
Example:
for i = 0 to n - 1
for j = 0 to n - 1
process i, j
For n = 3, the pairs are:
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
Nested loops are common when an algorithm needs to compare multiple elements or examine pairs of positions.
13. Time Complexity of a Single for Loop
Consider:
for i = 0; i < n; i++
operation
The loop executes approximately n times.
Therefore:
Time Complexity = O(n)
This is one of the most important patterns to recognize in DSA.
If the input size doubles, the number of iterations also approximately doubles.
14. Nested Loop Complexity
Consider:
for i = 0; i < n; i++
for j = 0; j < n; j++
operation
The outer loop runs n times.
For every outer iteration, the inner loop also runs n times.
Therefore:
n × n = n²
Time complexity:
O(n²)
Recognizing nested loops is an important part of analyzing DSA solutions.
15. Sequential Loops
Consider:
for i = 0 to n - 1
operation A
for i = 0 to n - 1
operation B
The loops run sequentially.
The total work is:
n + n = 2n
In Big-O notation:
O(n)
Constants are ignored in asymptotic complexity.
So two sequential loops are generally still O(n), not O(n²).
16. Dependent Nested Loops
Not every nested loop executes exactly n × n times.
Consider:
for i = 0; i < n; i++
for j = i + 1; j < n; j++
process
The inner loop becomes smaller as i increases.
The total number of iterations is approximately:
n(n - 1) / 2
Ignoring constants and lower-order terms:
O(n²)
This pattern is common in problems involving pairs of elements.
17. break in a for Loop
break stops the loop immediately.
For example:
for each element
if element == target
break
If the target is found early, the algorithm does not need to process the remaining elements.
For example:
[4, 8, 10, 15, 20]
target = 10
The loop stops after finding 10.
The worst-case time complexity may still be:
O(n)
but the actual number of iterations can be smaller.
18. continue in a for Loop
continue skips the current iteration and moves to the next iteration.
Example:
for each element
if element < 0
continue
process element
For:
[-3, 5, -1, 8]
the negative values are skipped.
Only:
5
8
are processed.
19. Common DSA Loop Patterns
Pattern 1: Traverse
for i = 0 to n - 1
process arr[i]
Pattern 2: Count
count = 0
for each element
if condition
count++
Pattern 3: Accumulate
sum = 0
for each element
sum += element
Pattern 4: Find Maximum
max = first element
for each remaining element
if element > max
max = element
Pattern 5: Search
for each element
if element == target
return found
Recognizing these patterns makes it easier to convert a problem statement into an algorithm.
20. Common Mistakes
Off-by-One Errors
For an array containing n elements, valid indexes are:
0 to n - 1
Therefore:
i < n
is normally used for traversal.
Using:
i <= n
can attempt to access an invalid index.
Starting From the Wrong Index
Consider:
for i = 1; i < n; i++
This intentionally skips index 0.
That may be correct when the first element is already used as an initial value, such as:
max = arr[0]
But it would be incorrect if every element needs to be processed.
Always understand why the loop starts at 0, 1, n - 1, or another index.
Wrong Loop Direction
For reverse traversal:
for i = n - 1; i >= 0; i--
Using i++ instead would move in the wrong direction.
Infinite Loops
A loop may never terminate if its condition never becomes false.
For example:
i = 0
while i < n
process i
If i is never updated, the loop does not progress.
A for loop makes the update step explicit, which helps reduce this type of mistake.
21. How to Analyze a for Loop
When you see a for loop in a DSA problem, ask three questions:
1. How many times does it execute?
Example:
for i = 0; i < n; i++
Approximately n times.
2. What happens inside the loop?
A constant-time operation:
O(1)
A nested loop:
O(n)
3. Are there multiple or nested loops?
For example:
one loop → O(n)
two nested → O(n²)
three nested → O(n³)
This gives a quick estimate of the algorithm's time complexity.
22. DSA Example: Find an Element
Given:
arr = [5, 8, 12, 20]
target = 12
Pseudocode:
for i = 0 to n - 1
if arr[i] == target
return i
return -1
The for loop performs the traversal.
The condition performs the comparison.
Together they form a basic searching algorithm.
Worst-case time complexity:
O(n)
23. DSA Example: Count Occurrences
Given:
arr = [2, 4, 2, 7, 2]
target = 2
Algorithm:
count = 0
for i = 0 to n - 1
if arr[i] == target
count++
return count
The result is:
3
The loop visits every element once.
Time complexity:
O(n)
24. for Loop and Algorithm Design
A for loop is not just a programming syntax feature.
In DSA, it represents a repeated operation in an algorithm.
For example:
for every element
compare
update
can represent:
- Finding a maximum
- Finding a minimum
- Counting elements
- Searching
- Calculating a sum
- Checking a property
- Building a result
Before writing code, identify:
- What needs to be repeated?
- How many times should it repeat?
- What changes after each iteration?
- When should the iteration stop?
- What is the time complexity?
These questions help turn a problem into a correct algorithm.
Quick Reference
| Pattern | Typical Complexity |
|---|---|
Single for loop |
O(n) |
Two sequential for loops |
O(n) |
Two nested for loops |
O(n²) |
| Three nested loops | O(n³) |
Loop over log n iterations |
O(log n) |
| Reverse traversal | O(n) |
Early break |
Best case may be smaller; worst case depends on traversal |
Key Takeaways
- A
forloop repeats an operation a controlled number of times. - It is one of the most common tools for implementing DSA algorithms.
- Array and string traversal frequently use
forloops. - A typical traversal of
nelements takesO(n)time. - Nested loops often lead to
O(n²)or higher complexity. - Sequential loops are generally added together when analyzing complexity.
breakcan terminate a loop early.continueskips the current iteration.- Correct loop boundaries are essential to avoid off-by-one errors.
- Always understand the initialization, condition, and update of a loop.
- When solving DSA problems, focus on what is being repeated and how many times it executes.
Practice Questions
- Print all elements of an array using a
forloop. - Print an array in reverse order.
- Find the sum of all elements.
- Find the maximum element.
- Find the minimum element.
- Count even numbers.
- Count occurrences of a target value.
- Find the first occurrence of a target.
- Print all elements greater than a given value.
- Find the number of duplicate pairs.
- Generate all pairs of elements.
- Analyze the time complexity of a given nested
forloop.
What's Next?
A for loop is useful when the number of iterations can be controlled using a counter or range.
The next lesson covers the while loop, which is useful when an algorithm continues executing based on a condition rather than a predetermined iteration count.
Related
-
Sum of Natural Numbers
Learn how to calculate the sum of the first N natural numbers using iteration and the mathematical formula.
-
Solid Rectangle
Learn how to print a solid rectangle pattern using nested loops and understand the row-column logic behind pattern problems.
-
Hollow Rectangle
Learn how to print a hollow rectangle pattern by printing characters only on its boundary using nested loops and conditions.
-
Sum of Consecutive Numbers
Learn how to calculate the sum of consecutive numbers using a loop and a mathematical formula, with complexity and examples.