I recently worked on an online problem for which answers were not provided, however, I would like to know where I went wrong. The prompt was strange, but I will do my best to explain it:
There is a machine that can fix all potholes along a road 3 units in length. A unit of Road will be represented with a period in a String. For example, "..." = one section of road 3 units in length. Potholes are marked with an "X" in the road, and also count as a unit of length. The task is to take a road of length N and fix all potholes with the fewest possible sections repaired by the machine. This problem is concerned with performance over correctness.
- Example 1: A road represented by ".X." would require 1 fix.
- Example 2: A road represented by "..X...X" would require 2 fixes.
- Example 3: A road represented by "XXX.XXXX" would require 3 fixes.
My approach (shown below) was to count sections of String in increments of 3 chars at once. If that sequence contained an "X", then it needed a fix and vice versa. To account for roads that aren't multiples of 3 in length I just kept the sequence reading and checked whatever was left. I'm also not sure how to make the program better for performance (other than replacing my sequence String with a StringBuilder)
public class Solution {
//Note: I had to re-write this from memory, as I was not given it back by the online problem checker
public int solution(String S) {
int fixes = 0;
String sequence = "";//Perhaps use StringBuilder?
for (int i = 0; i < S.length(); i++) {//read the entire incoming string
for (int j = 0; j < 3; j++) {//Count 3 chars at once
sequence += S.charAt(i);//Add said Chars to our sequence
}
if (sequence.contains("X")) {//Check for potholes
fixes++;//We can fix everything in this sequence
sequence = "";//reset our sequence
}
}
if (sequence.contains("X")) {//Check anything left, since not all roads are multiples of 3
fixes++;
}
return fixes;
}
}
I thought this was good enough for what was asked, and it passed all of the given example Strings, but apparently failed horribly upon review. I don't know what I've done wrong, though I feel like there's probably something small and stupid that I'm missing.
UPDATE:
I was indeed missing something obvious, I need to start reading at the first "X", something like this:
if (S.charAt(i) == 'X') {//Start counting at the first X
for (int j = 0; j < 3; j++) {//Count 3 chars at once
if (i + j <= S.length() - 1) {//no outofbounds exceptions please!
sequence += S.charAt(i + j);//Add said Chars to our sequence
}
}
}
Now I just need to make sure it meets performance requirements.