Category Archives: CodingBat: Java

CodingBat: Java. Array-3, Part I


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


The Array-3 section on CodingBat only contains 9 exercises, but some of those can be quite intricate. My solutions should be fairly easy to follow. If something is unclear, then take a piece of paper, write down a few sample arrays, and trace the execution by hand. With array-based problems, this can be a good preliminary step before staring to write code.

All solutions were successfully tested on 10 March 2013.

maxSpan:

public int maxSpan(int[] nums) {
	if (nums.length > 0) {
		int maxSpan = 1;
		for (int i = 0; i < nums.length; i++)
			for (int j = nums.length - 1; j > i; j--)
				if (nums[j] == nums[i]) {
					int count = (j - i) + 1;
					if (count > maxSpan) maxSpan = count;
					break;
				}
		return maxSpan;
	} else return 0;
}

In line 7 count gets increased by 1 because the span is inclusive of the last element. If the array is empty, the return value is 0.

fix34:

public int[] fix34(int[] nums) {
	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 3) {
			int temp = nums[i + 1];
			nums[i + 1] = 4;
			for (int j = i + 2; j < nums.length; j++)
				if (nums[j] == 4) nums[j] = temp;
		}
	return nums;
}

fix45:

public int[] fix45(int[] nums) {
	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 5 && i == 0
			|| nums[i] == 5 && nums[i - 1] != 4) {
			int pos5 = i;
			for (int j = 0; j < nums.length; j++)
				if (nums[j] == 4 && nums[j + 1] != 5) {
					int temp = nums[j + 1];
					nums[j + 1] = 5;
					nums[pos5] = temp;
					break;
				}
	}
	return nums;
}

canBalance:

public boolean canBalance(int[] nums) {
	for (int i = 0; i < nums.length; i++) { 
		int sum = 0;
		for (int j = 0; j < i; j++) sum += nums[j];
		for (int j = i; j < nums.length; j++) sum -= nums[j];
		if (sum == 0) return true;
	}
	return false;
}

The variable i indicates where the array is split.

linearIn:

public boolean linearIn(int[] outer, int[] inner) {
	int indexInner = 0;
	int indexOuter = 0;
	while (indexInner < inner.length && indexOuter < outer.length) {
		if (outer[indexOuter] == inner[indexInner]) {
			indexOuter++;
			indexInner++;
		} else indexOuter++;
	}
	return (indexInner == inner.length);
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. Array-2, Part III


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


tripleUp:

public boolean tripleUp(int[] nums) {
	for (int i = 0; i <= nums.length - 3; i++)
		if (nums[i + 1] == nums[i] + 1 && nums[i + 2] == nums[i] + 2)
			return true;
	return false;
}

shiftLeft:

public int[] shiftLeft(int[] nums) {
	if (nums.length > 0) {
		int first = nums[0];
		for (int i = 0; i < nums.length - 1; i++)
			nums[i] = nums[i + 1];
		nums[nums.length - 1] = first;
	}
	return nums;
}

tenRun:

public int[] tenRun(int[] nums) {
	boolean replace = false;
	int multiple = 0;

	for (int i = 0; i < nums.length; i++) {
		if (nums[i] % 10 == 0) {
			if (!replace) {
				replace = true;
				multiple = nums[i];
			} else
				multiple = nums[i];
		}
		if (nums[i] % 10 != 0 && replace) nums[i] = multiple;
	}
	return nums;
}

pre4:

public int[] pre4(int[] nums) {
		int count = 0;
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] != 4) count++;
			else break;
		}
		int[] result = new int[count];
		for (int i = 0; i < result.length; i++)
			result[i] = nums[i];
		return result;
}

post4:

public int[] post4(int[] nums) {
	int last4 = 0;
	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 4) last4 = i;
	
	int[] res = new int[nums.length - (last4 + 1)];
	for (int i = last4 + 1, j = 0; i < nums.length; i++, j++)
		res[j] = nums[i];
	
	return res;
}

notAlone:

public int[] notAlone(int[] nums, int val) {
	for (int i = 1; i < nums.length - 1; i++)
		if (nums[i] == val && nums[i - 1] != val
			&& nums[i + 1] != val)
			nums[i] = Math.max(nums[i - 1], nums[i + 1]);
	return nums;
}

zeroFront:

public int[] zeroFront(int[] nums) {
	int[] res      = new int[nums.length];
	int zeroPos    = 0;
	int nonZeroPos = res.length - 1;

	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 0)
			res[zeroPos++]    = 0;
		else
			res[nonZeroPos--] = nums[i];

	return res;
}

Note that the order of the non-zero numbers does not matter. For an alternative solution that modifies the given array, please see the comment by ‘aaaaaaaa’ below.

withoutTen:

public int[] withoutTen(int[] nums) {
	int[] copy = new int[nums.length];
	int index = 0;

	for (int i = 0; i < nums.length; i++)
		if (nums[i] != 10) {
			copy[index] = nums[i];
			index++;
		}
	return copy;
}

zeroMax:

public int[] zeroMax(int[] nums) {
	int largestOdd = 0;
	for (int i = nums.length - 1; i >= 0; i--) {
		if (nums[i] % 2 == 1 && nums[i] > largestOdd)
			largestOdd = nums[i];
		if (nums[i] == 0)
			nums[i] = largestOdd;
	}
	return nums;
}

evenOdd:

public int[] evenOdd(int[] nums) {
	int[] res   = new int[nums.length];
	int evenPos = 0;
	int oddPos  = res.length - 1;

	for (int i = 0; i < nums.length; i++)
		if (nums[i] % 2 == 0)
			res[evenPos++] = nums[i];
		else
			res[oddPos--]  = nums[i];
	return res;
}

The solution is similar to “zeroFront”, which is given above.


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. Array-2, Part II


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


no14:

public boolean no14(int[] nums) {
	int ones = 0;
	int fours = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 1) ones++;
		if (nums[i] == 4) fours++;
	}
	return ones == 0 || fours == 0;
}

isEverywhere:

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;
}

either24:

public boolean either24(int[] nums) {
	Boolean twos = false;
	Boolean fours = false;

	for (int i = 0; i < nums.length - 1; i++) {
		if (nums[i] == 2 && nums[i + 1] == 2) twos = true;
		if (nums[i] == 4 && nums[i + 1] == 4) fours = true;
	}
	return twos ^ fours;
}

The caret (^) in the return statement represents the logical XOR operator.

matchUp:

public int matchUp(int[] nums1, int[] nums2) {
	int count = 0;
	for (int i = 0; i < nums1.length; i++)
		if (nums1[i] != nums2[i]
			&& Math.abs(nums1[i] - nums2[i]) <= 2)
				count++;
	return count;
}

has77:

public boolean has77(int[] nums) {
	for (int i = 0; i < nums.length - 1; i++)
		if (nums[i] == 7 && nums[i + 1] == 7) return true;

	for (int i = 0; i < nums.length - 2; i++)
		if (nums[i] == 7 && nums[i + 2] == 7) return true;

	return false;
}

has12:

public boolean has12(int[] nums) {
	int one = 0;
	int two = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 1) one = i;
		if (nums[i] == 2) two = i;
	}
	return two > one;
}

The two variables keep track of the position of the number 1 and 2, respectively. After the for loop has finished, they will contain the position of the last 1 and last 2 in the array.

modThree:

public boolean modThree(int[] nums) {
	for (int i = 0; i <= nums.length - 3; i++) {
		boolean cond1 = nums[i] % 2 == 0 && nums[i + 1] % 2 == 0
				&& nums[i + 2] % 2 == 0;
		boolean cond2 = nums[i] % 2 == 1 && nums[i + 1] % 2 == 1
				&& nums[i + 2] % 2 == 1;
		if (cond1 || cond2) return true;
	}
	return false;
}

haveThree:

public boolean haveThree(int[] nums) {
	int count = 0;
	int pos = -2; // in case nums[0] == 3

	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 3) {
			count++;
			if (i - pos == 1) return false;
			pos = i;
		}
	}

	return count == 3;
}

twoTwo:

public boolean twoTwo(int[] nums) {
	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 2) {
			int count = 0;
			for (int j = i; j < nums.length; j++)
				if (nums[j] == 2) count++;
				else break;
			i += count;
			if (count < 2) return false;
		}
	return true;
}

sameEnds:

public boolean sameEnds(int[] nums, int len) {
	for (int i = 0, j = nums.length - len; i < len; i++, j++)
		if (nums[i] != nums[j]) return false;
	return true;
}

The for loop traverses the array from back to front and front to back simultaneously.


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. Array-2, Part I


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


The Array-2 section of CodingBat present 30 problems of varying difficulty. Most you should be able to solve straight away, while a few may take you up to half an hour or so.

All solutions were successfully tested on 3 March 2013.

countEvens:

public int countEvens(int[] nums) {
	int count = 0;
	for (int i = 0; i < nums.length; i++)
		if (nums[i] % 2 == 0) count++;
	return count;
}

bigDiff:

public int bigDiff(int[] nums) {
  int max = nums[0];
  int min = nums[0];
  
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] > max) max = nums[i];  
    if (nums[i] <= min) min = nums[i];
  }
  return max - min;
}

It wasn’t clear to me why the instructions mentioned the inbuilt Math.min(int a, int b) and Math.max(int a, int b) functions. If you use those, you’ll only end up with a more complicated method.

A common mistake people make in this kind of exercise is to initialize the maximum or minimum value with 0 and a very large number, respectively, instead of using an actual value from the array. Given the test cases on CodingBat, you would get away with, for instance, initializing “max” with 0 and “min” with 1000, but if the array you process only consists of numbers that are either all smaller than “max” or all larger than “min”, you’d get the wrong result.

centeredAverage:

public int centeredAverage(int[] nums) {
	int max = nums[0];
	int min = nums[0];
	int sum = 0;

	for (int i = 0; i < nums.length; i++) {
		sum += nums[i];
		if (nums[i] > max) max = nums[i];
		if (nums[i] < min) min = nums[i];
	}
	return (sum - (max + min)) / (nums.length - 2);
}

sum13:

public int sum13(int[] nums) {
	int total = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] != 13) total += nums[i];
		else if (i <= nums.length - 1) i++;
	}
	return total;
}

sum67:

public int sum67(int[] nums) {
	int sum = 0;
	for (int i = 0; i < nums.length; i++) {
		if (nums[i] != 6) sum += nums[i];
		else
			while (nums[i] != 7) i++;
	}
	return sum;
}

has22:

public boolean has22(int[] nums) {
	for (int i = 0; i <= nums.length - 2; i++)
		if (nums[i] == 2 && nums[i + 1] == 2) return true;
	return false;
}

lucky13:

public boolean lucky13(int[] nums) {
	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 1 || nums[i] == 3) return false;
	return true;
}

sum28:

public boolean sum28(int[] nums) {
	int sum = 0;
	for (int i = 0; i < nums.length; i++)
		if (nums[i] == 2) sum += 2;
	return sum == 8;
}

more14:

public boolean more14(int[] nums) {
	int ones = 0;
	int fours = 0;

	for (int i = 0; i < nums.length; i++) {
		if (nums[i] == 1) ones++;
		if (nums[i] == 4) fours++;
	}
	return ones > fours;
}

only14:

public boolean only14(int[] nums) {
	for (int i = 0; i < nums.length; i++)
		if (nums[i] != 1 && nums[i] != 4) return false;
	return true;
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


CodingBat: Java. String-3, Part II


For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.


sameEnds:

public String sameEnds(String string) {
	String result = "";
	int len = string.length();
	for (int i = 0; i <= len / 2; i++)
		for (int j = len / 2; j < len; j++)
			if (string.substring(0, i).equals(string.substring(j)))
				result = string.substring(0, i);
	return result;
}

The variable in line 3 makes the code a bit more compact.

mirrorEnds:

public String mirrorEnds(String string) {
	String result = "";
	int len = string.length();
	for (int i = 0, j = len - 1; i < len; i++, j--)
		if (string.charAt(i) == string.charAt(j))
			result += string.charAt(i);
		else break;
	return result;
}

maxBlock:

public int maxBlock(String str) {
	int max = 0;
	for (int i = 0; i < str.length(); i++) {
		int count = 0;
		for (int j = i; j < str.length(); j++) {
			if (str.charAt(i) == str.charAt(j)) count++;
			else break;
		}
		if (count > max) max = count;
	}
	return max;
}

sumNumbers:

public int sumNumbers(String str) {
		int sum = 0;
		for (int i = 0; i < str.length(); i++) {
			if (Character.isDigit(str.charAt(i))) {
				int count = 0;
				for (int j = i; j < str.length(); j++) {
					if (Character.isDigit(str.charAt(j))) count++;
					else break;
				}
				sum += Integer.parseInt(str.substring(i, i + count));
				i += count;
			}
		}
		return sum;
}

notReplace:

public String notReplace(String str) {
	String result = "";
	str = " " + str + "  "; // avoid issues with corner cases
	for (int i = 0; i < str.length() - 2; i++) {
		if (str.charAt(i) == 'i') {
			if (str.charAt(i + 1) == 's'
					&& !Character.isLetter(str.charAt(i + 2))
					&& !Character.isLetter(str.charAt(i - 1))) {
				result += "is not";
				i += 1;
			} else result += "i";
		} else result += str.charAt(i);
	}
	return result.substring(1);
}

For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.