ZeroToSky
Data Structures and Algorithms Tutorial 3 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 →

While Loop

Learn how while loops repeatedly execute DSA operations while a condition remains true, including traversal, pointer movement, termination, and complexity.

Gaurav 6 min read Sign in to save
On this page

While Loop

A while loop repeatedly executes an operation as long as a condition remains true.

In DSA, while loops are useful when the number of iterations is not known in advance and depends on the state of the algorithm.

Common uses include:

  • Traversing data using a condition
  • Moving pointers
  • Processing elements until a condition changes
  • Repeating an operation until a result is found
  • Implementing two-pointer techniques
  • Sliding-window algorithms
  • Processing linked lists
  • Controlling iterative algorithms

The basic idea is:

while condition is true
    perform operation

1. Basic Structure

A while loop has two important parts:

while condition
    operation

The condition is checked before every iteration.

Example:

i = 0

while i < 5
    process i
    i++

The values processed are:

0
1
2
3
4

When:

i = 5

the condition:

i < 5

becomes false and the loop stops.


2. How a while Loop Works

Consider:

i = 0

while i < 3
    process i
    i++

Execution:

i = 0
   ↓
0 < 3 → true
   ↓
process 0
   ↓
i++
   ↓
i = 1
   ↓
1 < 3 → true
   ↓
process 1
   ↓
i++
   ↓
i = 2
   ↓
2 < 3 → true
   ↓
process 2
   ↓
i++
   ↓
i = 3
   ↓
3 < 3 → false
   ↓
Stop

The important point is that the loop continues based on a condition, not simply a fixed number of iterations.


3. while Loop for Array Traversal

A while loop can be used to traverse an array.

Given:

arr = [10, 20, 30, 40, 50]

We can write:

i = 0

while i < arr.length
    process arr[i]
    i++

The loop processes:

10
20
30
40
50

The condition:

i < arr.length

controls whether another element remains to be processed.


4. while Loop vs for Loop

Both can perform repeated operations, but they are useful in different situations.

for loop

Usually preferred when the iteration structure is clearly defined.

for i = 0 to n - 1
    process arr[i]

while loop

Useful when the continuation condition is more important than a fixed iteration count.

while condition
    perform operation

For example, an algorithm may continue until:

target is found

or:

window becomes valid

or:

left pointer crosses right pointer

The choice depends on the algorithm.


5. Pointer Movement

One of the most important DSA uses of while loops is pointer movement.

For example:

left = 0
right = n - 1

while left < right
    process arr[left] and arr[right]

    left++
    right--

The loop continues while:

left < right

This pattern is common in:

  • Two-pointer problems
  • Palindrome problems
  • Array problems
  • Searching problems

6. Two-Pointer Example

Consider:

arr = [1, 2, 3, 4, 5]

We start with:

left = 0
right = 4

Then:

while left < right

The pointers move toward each other:

left →        ← right

1  2  3  4  5
↑           ↑

   1  2  3  4  5
      ↑     ↑

   1  2  3  4  5
         ↑

The loop stops when:

left >= right

This is a common condition-based iteration pattern.


7. Palindrome Pattern

A palindrome reads the same from both directions.

For example:

"madam"

A two-pointer solution can use a while loop:

left = 0
right = length - 1

while left < right

    if string[left] != string[right]
        return false

    left++
    right--

return true

The loop continues while there are still two characters to compare.

The important condition is:

left < right

This pattern is commonly used for palindrome-related problems.


8. Searching with a while Loop

A search can also be implemented using a while loop.

i = 0

while i < n

    if arr[i] == target
        return i

    i++

return -1

The loop continues until:

  • The target is found, or
  • All elements have been checked.

For an array of size n, the worst-case time complexity is:

O(n)

9. Processing Until a Condition Changes

A while loop is useful when an algorithm needs to continue until some state changes.

For example:

while value > 0
    process value
    value = value / 2

The number of iterations depends on how quickly value changes.

If the value is repeatedly divided by 2, the number of iterations is approximately:

O(log n)

This type of pattern appears in algorithms where the problem size decreases during each iteration.


10. Sliding Window Pattern

while loops are frequently used in sliding-window algorithms.

A simplified pattern is:

right = 0
left = 0

while right < n

    add arr[right]

    while window is invalid
        remove arr[left]
        left++

    right++

The inner while loop shrinks the window until the required condition is satisfied.

The important idea is:

Expand window
      ↓
Check condition
      ↓
Invalid?
      ↓
Shrink window

This pattern is common in substring and subarray problems.


11. Linked List Traversal

A while loop is a natural choice for traversing a linked list.

current = head

while current != null
    process current
    current = current.next

The loop continues while a valid node exists.

The termination condition is:

current == null

Once the end of the linked list is reached, the loop stops.

For a linked list containing n nodes:

Time Complexity = O(n)

12. Nested while Loops

A while loop can contain another while loop.

Example:

while condition1

    while condition2
        process

The complexity depends on how many times each loop executes.

If both loops independently process n elements:

O(n²)

However, nested loops do not automatically mean O(n²). The actual number of iterations must be analyzed.


13. break in a while Loop

break immediately terminates the loop.

Example:

while i < n

    if arr[i] == target
        break

    i++

If the target is found, there is no need to continue.

This is useful when an algorithm has found the required result before reaching the normal loop boundary.


14. continue in a while Loop

continue skips the current iteration and moves to the next iteration.

Example:

while i < n

    if arr[i] < 0
        i++
        continue

    process arr[i]

    i++

When using continue, make sure the loop's control variable is updated appropriately.

Otherwise, the loop may never terminate.


15. Infinite Loops

A while loop can become infinite if its condition never becomes false.

For example:

i = 0

while i < n
    process i

If i is never changed, the condition remains true.

A correct version is:

i = 0

while i < n
    process i
    i++

Always identify what will eventually make the loop condition false.


16. Loop Termination

When designing a while loop, ask:

  1. What is the starting state?
  2. What condition keeps the loop running?
  3. What changes during each iteration?
  4. What condition causes the loop to stop?

For example:

left = 0
right = n - 1

while left < right

    process

    left++
    right--

Here:

  • Starting state: left = 0, right = n - 1
  • Continuation condition: left < right
  • State change: left++, right--
  • Termination: left >= right

Understanding these four parts helps prevent incorrect loops.


17. Time Complexity of while Loops

The complexity of a while loop depends on how many iterations it performs.

Linear

i = 0

while i < n
    i++

Iterations:

n

Time complexity:

O(n)

Logarithmic

i = n

while i > 1
    i = i / 2

The value is repeatedly divided by 2.

Time complexity:

O(log n)

Quadratic

If a loop contains another loop and both perform approximately n iterations:

while condition
    while another condition
        process

The complexity can be:

O(n²)

Always analyze the number of iterations rather than judging complexity from syntax alone.


18. Common DSA Patterns

Pattern 1: Pointer Traversal

i = 0

while i < n
    process arr[i]
    i++

Pattern 2: Two Pointers

left = 0
right = n - 1

while left < right
    process
    move pointers

Pattern 3: Search Until Found

while elements remain
    if target found
        return result

Pattern 4: Shrink a Range

while condition
    reduce search space

Pattern 5: Process Until State Changes

while state is valid
    update state

Recognizing these patterns is useful when converting a problem statement into an algorithm.


19. Common Mistakes

Forgetting to Update the Loop State

Incorrect:

i = 0

while i < n
    process arr[i]

Correct:

i = 0

while i < n
    process arr[i]
    i++

Wrong Boundary Condition

For two pointers, these conditions are different:

left < right

and:

left <= right

The correct one depends on whether the middle element needs to be processed.


Updating the Wrong Pointer

In a two-pointer algorithm, moving the wrong pointer can cause:

  • Incorrect results
  • Missed elements
  • Infinite loops

Always determine why each pointer moves.


Incorrect continue Usage

If a control variable is not updated before continue, the loop may repeatedly process the same state.


20. while Loop and Algorithmic Thinking

When using a while loop in DSA, do not think only about syntax.

Think about the state of the algorithm.

Ask:

What state am I tracking?
        ↓
What condition keeps the algorithm running?
        ↓
How does the state change?
        ↓
When does the algorithm terminate?

For example, in a two-pointer problem:

State:
left, right

Condition:
left < right

Update:
left++, right--

Termination:
left >= right

This way of thinking is more useful than simply memorizing loop syntax.


Quick Reference

Use Case Typical Pattern
Array traversal while i < n
Linked list while current != null
Two pointers while left < right
Search while elements remain
Sliding window while window is invalid
Shrinking problem while size > 1
Early termination break
Skip iteration continue

Key Takeaways

  • A while loop repeats an operation while a condition remains true.
  • It is useful when the number of iterations depends on the algorithm's state.
  • while loops are common in pointer-based DSA techniques.
  • Two-pointer algorithms frequently use while.
  • Linked-list traversal commonly uses while.
  • Sliding-window algorithms often use while to expand or shrink a window.
  • The loop must change its state so that the termination condition can eventually become true.
  • Incorrect boundaries can cause missed elements or incorrect results.
  • An infinite loop occurs when the termination condition is never reached.
  • Time complexity depends on the number of iterations.
  • Always identify the loop's state, condition, update, and termination point.

Practice Questions

  1. Traverse an array using a while loop.
  2. Search for an element using a while loop.
  3. Find the maximum element using a while loop.
  4. Reverse an array using two pointers.
  5. Check whether a string is a palindrome.
  6. Count the occurrences of a target value.
  7. Find the first occurrence of an element.
  8. Implement a two-pointer pair-sum solution.
  9. Determine the time complexity of a given while loop.
  10. Identify and fix an infinite loop.

What's Next?

A while loop provides condition-based iteration. Another useful loop structure is the do-while loop, where the algorithm executes the operation once before checking the condition.

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

Goes straight to the author. Not published anywhere.