Skipping Elements in an Array Using a Loop
Learn how to efficiently skip irrelevant data while iterating through an array using conditional jumps and optimized increments.
Ignoring the Noise
Not every element in an array is relevant to your algorithmic problem. Filtering out noise quickly and efficiently is a core concept in Data Structures and Algorithms.
Method 1: The 'Continue' Statement
The most readable way to skip elements is using a guard clause with the continue keyword.
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) continue; // Skip all zeros
print(nums[i]);
}
This method is best when the decision to skip depends on the value of the data rather than its position.
Method 2: Adjusting the Increment
If the skipping follows a mathematical pattern (e.g., checking only even indices), you should modify the update step rather than using an if statement.
for (int i = 0; i < nums.length; i += 2) {
print(nums[i]); // Prints index 0, 2, 4...
}
This is significantly faster because the loop executes half as many times (N/2), whereas the continue method still requires N full iterations.
Method 3: Skipping Duplicates
In sorted arrays, a common requirement (especially in problems like 3Sum) is to skip duplicate values to prevent duplicate results.
while (i < nums.length - 1 && nums[i] == nums[i+1]) {
i++; // Skip over the duplicate
}
This technique manually advances the loop counter to safely bypass repeated blocks of data.
The Takeaway
Efficiency is not just about Big O; it's about minimizing unnecessary operations. By strategically using continue or modifying your loop counters, you write code that is faster, cleaner, and less prone to edge-case bugs.
Use the 'continue' keyword. It stops the current iteration immediately and jumps to the next evaluation of the loop.
If you are skipping based on position (e.g., every 3rd element), adjusting the counter is much faster. If skipping based on value, you must use an if-statement.
Use a while loop inside your main loop to check if the current element equals the next element, and increment your pointer until they differ.
Skipping by value (continue) is still O(N). Skipping by large counter increments (i += 2) is technically O(N/2), which simplifies to O(N) in Big O notation.
Yes, by manually adding a specific value to your loop counter (e.g., i = i + 5) you can skip blocks of data entirely.
