As the name suggests, look for edges cases, let us understand with an example
Example1: find max number in an array of natural numbers, array: [2, 1, 4, 6, 7]
First Solution:
// language : golang
maxValue := 0
for i := 0; i <= len(array); i++ {
if maxValue < array[i] {
maxValue = array[i]
}
}
return maxValue
Above code will crash when i = len(array) because array index will range from 0 to len(array) -1 (not len(array))
Correct solution
maxValue := 0
for i := 0; i < len(array); i++ {
if maxValue < array[i] {
maxValue = array[i]
}
}
return maxValue
Example 2 – For doing any operation in matrix for each cell we need to check that it’s index is valid at the start of the function as below:-
// other code parts
import "errors"
var (
ErrRowOutOfBounds = errors.New("cell' row out of bounds")
ErrColOutOfBounds = errors.New("cell' column out of bounds")
)
func opInMatrix(i, j, numRows, numCols int, matrix [][]int) error {
if i < 0 || i >= numRows {
return ErrRowOutOfBounds
}
if j < 0 || j >= numCols {
return ErrColOutOfBounds
}
/// do the actual operation
}