ZeroToSky
Data Structures and Algorithms Tutorial 1 of 486
Foundations 17/41
Fundamentals

All 13 lessons →

Maths, Pattern & Recursion

All 28 lessons →

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

All 47 lessons →

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

All 22 lessons →

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

All 20 lessons →

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

All 10 lessons →

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

All 7 lessons →

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

All 19 lessons →

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

All 16 lessons →

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

All 34 lessons →

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

All 15 lessons →

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

All 8 lessons →

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

All 26 lessons →

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

All 14 lessons →

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

All 20 lessons →

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

All 14 lessons →

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

All 25 lessons →

Backtracking
  • Backtracking Basics
  • Permutations
  • Rat in a Maze
  • Word Search
  • N-Queen Problem
  • Sudoku Solver
  • Word Break
  • Knight's Tour
  • Palindromic Partitions
  • M-Coloring

All 10 lessons →

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

All 16 lessons →

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

All 32 lessons →

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

All 22 lessons →

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

All 44 lessons →

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

All 9 lessons →

Number Theory
  • nCr
  • Euler's Totient
  • Sieve of Eratosthenes
  • Pascal's Triangle
  • Modular Exponentiation
  • Segmented Sieve

All 6 lessons →

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

All 9 lessons →

Conditional Statements in DSA

Learn how conditional statements help algorithms make decisions using comparisons, Boolean conditions, if-else logic, and multiple conditions.

Gaurav 5 min read Sign in to save
On this page

Conditional Statements

Conditional statements allow an algorithm to make decisions based on whether a condition is true or false.

In DSA, conditions are commonly used to:

  • Compare values
  • Check whether an element satisfies a requirement
  • Choose between two operations
  • Update a result
  • Decide which path an algorithm should follow

For example:

if current > maximum
    maximum = current

The algorithm checks a condition and performs an operation only when the condition is true.


What Is a Condition?

A condition is an expression that evaluates to either:

true

or:

false

For example:

x > 10

If x = 15:

15 > 10 → true

If x = 5:

5 > 10 → false

Algorithms use this result to decide what to do next.


1. if Statement

An if statement executes an operation when a condition is true.

Syntax

if condition
    operation

Example

if number > 0
    print "Positive"

If number is 10, the condition is true and the operation is performed.

If the condition is false, nothing happens.

DSA Example

While processing an element:

if element > maximum
    maximum = element

This is a common compare-and-update pattern.


2. if-else Statement

An if-else statement provides two possible paths.

if condition
    operation A
else
    operation B

Example:

if number % 2 == 0
    print "Even"
else
    print "Odd"

The algorithm chooses exactly one of the two paths.

This is useful when a problem has two possible outcomes.


3. else-if

When an algorithm needs to check multiple conditions, else-if can be used.

if condition1
    operation A
else if condition2
    operation B
else
    operation C

The conditions are checked from top to bottom.

Once a condition is true, its corresponding block is executed.

Example

if number > 0
    print "Positive"
else if number < 0
    print "Negative"
else
    print "Zero"

For number = 0, the output is:

Zero

4. Comparison Operators

Conditions commonly use comparison operators.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example:

if current == target
    element found

Here, the algorithm checks whether the current value matches the target.


5. Logical Operators

Multiple conditions can be combined using logical operators.

AND — &&

Both conditions must be true.

if x > 0 && x < 100
    process x

OR — ||

At least one condition must be true.

if x == 0 || x == 1
    process x

NOT — !

Reverses a Boolean condition.

if !visited
    process node

These operators are useful when an algorithm needs to make a decision based on multiple conditions.


6. Boolean Conditions

A Boolean value has only two possible states:

true
false

For example:

visited = false

An algorithm can then check:

if !visited
    visit the node

Boolean conditions are commonly used to represent algorithm state.

Examples include:

found
visited
isValid
isSorted
hasElement

7. Nested Conditions

A condition can contain another condition.

if condition1
    if condition2
        operation

For example:

if number > 0
    if number % 2 == 0
        print "Positive even number"

Nested conditions should be used carefully. Too many levels of nesting can make an algorithm difficult to understand.


8. Conditional Decision Pattern

A common pattern in DSA is:

Check condition
      |
   +--+--+
   |     |
 True   False
   |     |
Action  Other action

For example:

if current > maximum
    maximum = current
else
    continue

This pattern appears repeatedly when designing algorithms.


9. Condition Ordering

The order of conditions can affect the result.

Consider:

if number >= 0
    print "Non-negative"
else if number > 100
    print "Greater than 100"

The second condition can never execute because every number greater than 100 is already greater than or equal to 0.

A better ordering is:

if number > 100
    print "Greater than 100"
else if number >= 0
    print "Non-negative"

When using multiple conditions, make sure earlier conditions do not make later conditions unreachable.


10. Boundary Conditions

In DSA, conditions often involve boundaries.

For example:

if index < n
    access arr[index]

Using the wrong boundary can cause errors.

Common boundary cases include:

  • Empty input
  • First element
  • Last element
  • Minimum value
  • Maximum value
  • Equal values

Always check whether the condition includes or excludes the boundary.

For example:

>

and:

>=

do not mean the same thing.


11. Conditional Logic in Pseudocode

When solving DSA problems, write the decision logic in pseudocode before implementing it in a programming language.

Example:

Find maximum:

max = first element

for each element:
    if element > max:
        max = element

return max

The important part is the decision:

element > max

The same algorithm can later be implemented in C#, Java, Python, C++, or another language.

This helps separate algorithmic thinking from programming syntax.


12. Common Mistakes

Using the wrong comparison

Be careful with:

>
>=
<
<=

A small difference can change the result.

Incorrect condition ordering

A broad condition placed before a more specific condition may prevent the specific condition from executing.

Ignoring boundary cases

Always consider what happens when a value is exactly at the boundary.

Too many nested conditions

Deeply nested conditions can make algorithm logic difficult to follow. Look for ways to simplify the decision-making logic.


Quick Reference

Concept Example
if if x > 0
if-else if x > 0 ... else ...
else-if if x > 0 ... else if x < 0 ...
Equal x == y
Not equal x != y
Greater x > y
Less x < y
AND x > 0 && x < 10
OR x == 0 | | x == 1
NOT !visited

Key Takeaways

  • Conditional statements allow algorithms to make decisions.
  • A condition evaluates to true or false.
  • if executes an operation when a condition is true.
  • if-else provides two possible paths.
  • else-if handles multiple conditions.
  • Comparison operators are used to compare values.
  • Logical operators combine multiple conditions.
  • Boolean variables can represent algorithm state.
  • Condition ordering can affect the correctness of an algorithm.
  • Boundary conditions are especially important in DSA.
  • Conditional logic is a fundamental building block of algorithm design.

Practice Questions

  1. Check whether a number is positive, negative, or zero.
  2. Check whether a number is even or odd.
  3. Find the larger of two numbers.
  4. Find the largest of three numbers.
  5. Check whether a number is divisible by both 3 and 5.
  6. Check whether a value lies within a given range.
  7. Determine whether a number is between two boundaries.
  8. Write pseudocode using if-else to find the larger of two values.
  9. Identify an incorrect condition ordering in a given algorithm.
  10. Identify the boundary conditions for a given DSA problem.

What's Next?

Conditional statements provide the decision-making part of an algorithm.

The next lesson introduces Loops and Iteration, which allow algorithms to repeatedly execute operations while a condition remains satisfied.

Related

Found a problem on this page, or something that could be clearer?

Goes straight to the author. Not published anywhere.