0

I'm doing a problem on codingbat.com and am confused with why this solution to the problem does not give an index out of bounds error. Wouldn't the first for loop search for an index that is beyond the length of the passed array?

Here's the problem:

We'll say that a value is "everywhere" in an array if for every pair of adjacent elements in the array, at least one of the pair is that value. Return true if the given value is everywhere in the array.

Here's my working solution:

public boolean isEverywhere(int[] nums, int val) {
 boolean flag1 = true;
 boolean flag2 = true;
 for (int i = 0; i < nums.length; i += 2) {
    if (nums[i] != val) flag1 = false;
 }
 for (int i = 0; i < nums.length - 1; i += 2) {
    if (nums[i + 1] != val) flag2 = false;
 }
 return flag1 || flag2;
}

Thanks!

Ethan
  • 223
  • 1
  • 2
  • 4

2 Answers2

3

No. The test happens after i is incremented. So, once i is not less than the length of the nums array the loop stops. The second loop uses i + 1 at if (nums[i + 1] != val) which is why it needs to test that i is less than the length minus one.

Also you can make the method static (since it uses no instance state).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

It wouldn't because while i += 2 is written after i < nums.length, the loop still checks that i is less than the given length(nums.length) before going onto the body of the loop even after 2 has been added on.

Ali Camilletti
  • 116
  • 1
  • 3
  • 11