In today's contest, I found the algorithm to B relatively quickly... and then proceeded to get about 5 WAs due to off-by-one implementation errors :skull:
Are there any tips you guys use to avoid silly off-by-one errors with indices? IDK why but something about it just doesn't click for me in-contest. (Surely I'm not the only one with this issue...)









one thing i have learned is to verify your code in extreme cases when the index is equal to 0 or n-1. for example, if you calculating length from index i (inclusive) to end of a string. quickly check that your expression is equal to 1 when i == n-1.
I generally come up with a trivial test case in my head to check if the algorithm works properly if I am unsure of whether a +1 is necessary. Usually off by one will break all the test cases uniformly, so this trick often works well enough.
in today's contest, i created a string f = "a" + input string. later did operations on f
for problems like this instead of unnecessary casework (such as the 0 and n-1 checks in your code), I like to "append"
to the set of # positions, in my submission I just do it to the set of positions but in some problems I will modify the string too. i.e. ..... -> #.....#, .#..# -> #.#..## then I just get difference accounting for these + 1, this avoids any off by one err 332898582
I think the reason one off errors can be difficult to spot is not clearly defining the bounds.
In many graph problems, the "end" of the graph is when you reach the final square, in this case the end of the graph is when you exit the graph.
The first step is to label these variants and give them a name, so when you encounter a variant you can map it to your definition.
For instance when iterating through an array, the distance to the first element is i, and distance to last element is n — i — 1. Distance to leave array at beginning is i + 1, and leave end is n — i.
Be deliberate, greater than or equal vs greater than. inclusive bounds ], vs exclusive bounds ). There are 10 numbers from 0..9, and 11 numbers from 0..10. Simple things that can bite you in the ass