Loop backwards using indices
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Looping backwards using indices means iterating from the last element to the first by decrementing an index variable. This is useful when removing elements during iteration (to avoid index shifting), processing data in reverse order, or implementing algorithms like reverse string comparison. Every major language supports backward loops through for loops with decrementing counters, and many provide built-in utilities like Python's reversed() or JavaScript's Array.reverse().
Python
Using range() with Negative Step
range(4, -1, -1) generates 4, 3, 2, 1, 0. The stop value -1 is exclusive, so it stops after 0.
Using reversed()
Safe Removal During Backward Iteration
Removing elements during a forward loop skips elements because indices shift. Backward iteration avoids this because removing an element only affects indices after the current position.
JavaScript
for Loop
Safe Removal with splice()
Java
ArrayList Backward Removal
C / C++
C#
Swift
Go
When to Use Backward Loops
| Use Case | Why Backward |
| Removing elements during iteration | Prevents index shifting after removal |
| Reverse string/array processing | Natural order for palindrome checks, reverse printing |
| Stack-like processing (LIFO) | Process most recently added items first |
| Dependency resolution | Process dependencies before dependents |
Common Pitfalls
- Off-by-one error on the start index: The last valid index is
length - 1, notlength. Starting atlengthcauses anIndexOutOfBoundsExceptionor buffer overflow. - Using unsigned integers for the loop counter: In C/C++,
size_tis unsigned. The conditioni >= 0is always true for unsigned types, creating an infinite loop. Usefor (size_t i = size; i-- > 0; )or cast to a signed type. - Removing elements during a forward loop: Forward iteration skips elements after removal because indices shift down. Always iterate backward when removing elements by index.
- Forgetting that
range()stop is exclusive in Python:range(4, 0, -1)produces4, 3, 2, 1— it stops before0. To include index0, userange(4, -1, -1). - Modifying the loop variable inside the body: Changing
iinside a backward loop can cause skipped elements or infinite loops. Let the loop control statement handle decrementing.
Summary
- Loop backward with
for (int i = length - 1; i >= 0; i--)in most languages - In Python, use
range(len(items) - 1, -1, -1)orreversed(range(len(items))) - Backward loops are essential for safely removing elements during iteration
- Watch for off-by-one errors and unsigned integer underflow in C/C++
- Prefer language-specific utilities (
reversed(),.reversed(),stride()) for readability

