-
Early exit on a sentinel value.
int scanUntilZero(int[] A) {
int s = 0;
for (int i = 0; i < A.length; i++) {
s += A[i];
if (A[i] == 0) break;
}
return s;
}
-
Nested search over the prefix. Early exit on first duplicate.
int hasDuplicatePrefix(int[] A) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < i; j++) {
if (A[i] == A[j]) return 1;
}
}
return 0;
}
-
Pair counting with a break depending on a threshold \(S\).
void countPairsUpToS(int[] A, int S) {
int c = 0;
for (int i = 0; i < A.length; i++) {
for (int j = i + 1; j < A.length; j++) {
c++;
if (A[i] + A[j] > S) break;
}
}
}
-
Divide by 2 until zero.
void halfWhile(int n) {
while (n > 0) {
n = n / 2;
}
}
- Tricky one!
void sqrtStepper(int n) {
for (int i = 1; i * i <= n; i++) {
// O(1) work
}
}
-
Changing inner loop.
void doublingInner(int n) {
for (int i = 1; i <= n; i++) {
int k = 1;
while (k < i) {
k = k * 2;
}
}
}
-
Triangular nested loop with a possible early break based on a changing accumulator.
void triangularPlusBreak(int n) {
int t = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
t += i + j;
if (t % 1000 == 0) break;
}
}
}
-
Fixed-size inner loop of constant \(M\) iterations.
int fixedInnerConstant(int[] A) {
int M = 250; // constant
int s = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < M; j++) {
s += A[i] + j;
}
}
return s;
}
-
Two separate parameters: total work depends on both \(n\) and \(m\).
void twoParameters(int n, int m) {
int x = 0;
for (int i = 0; i < n; i++) x++;
for (int j = 0; j < m; j++) x++;
}
-
Fully nested two-parameter loops.
void nestedTwoParameters(int n, int m) {
long x = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
x += i + j;
}
}
}
-
Three nested loops with possible immediate return.
void threeNestedWithBreak(int n) {
long x = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k < j; k++) {
x++;
if (x == 5) return;
}
}
}
}
-
Mixed for/while.
void mixedForWhile(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
int t = i;
while (t > 0) {
t = t / 3;
count++;
}
}
}
-
Early exit when a running sum exceeds a threshold; otherwise full scan.
int sumWithSentinel(int[] A) {
int s = 0;
for (int i = 0; i < A.length; i++) {
s += A[i];
if (s > 1000000) return s;
}
return s;
}
-
Work per iteration grows with the index: total work is the sum.
void variableWorkPerIter(int n) {
for (int i = 1; i <= n; i++) {
for (int t = 0; t < i; t++) {
// 1 step per t
}
}
}