This condition is required to be checked , otherwise l and r will cross each other and loop will never terminate .
if ( $ l == ( $ r - 1 + $ n ) % $ n ) { return $ cnt ; } $ l = ( $ l + 1 ) % $ n ; $ r = ( $ r - 1 + $ n ) % $ n ; }