Another alternative: use `RLE` (run-length-encoding; with thanks to the comments for the correct naming), borrowed originally from a very simple data compressor of the same name. Here's the code, albeit in the `R` language. (For non-users, `1L` just forces integer-class, `x[-k]` means all of vector `x` *except* index 'k' ) Here's the base package code for the function `rle(x)` : First line: generate logical vector of "is x[j] == x[j-1] ? " y <- x[-1L] != x[-n] ; `which` returns index values when argument is TRUE, and `c` concatenates vectors (is.na just catches N/A values in case the input was skeevy) i <- c(which(y | is.na(y)), n) ; finally, create a structure. First element calculates run lengths by comparing sequential index values in `i` ; second element returns the value of the input vector every time that run terminates structure(list(lengths = diff(c(0L, i)), values = x[i]), class = "rle") then add a line to find `max(lengths[values==0])`.