def check_ranges(total_length, ranges):
  """
  Check to make sure the given ranges are valid.
  
  Inputs:
  - total_length: Integer giving total length
  - ranges: Sorted list of tuples giving (start, end) for each range.
  
  Returns: Boolean telling whether ranges are valid.
  """
  # The start of the first range must be 0
  if ranges[0][0] != 0:
    return False
  
  # The end of the last range must fill the length
  if ranges[-1][1] != total_length:
    return False
  
  for i, cur_range in enumerate(ranges):
    # The ranges must be distinct
    if i + 1 < len(ranges) and cur_range[0] == ranges[i + 1][0]:
      return False
    # The ranges must cover all the pixels
    if i + 1 < len(ranges) and cur_range[1] < ranges[i + 1][0]:
      return False
    # Each range should not overlap with its second neighbor
    if i + 2 < len(ranges) and cur_range[1] >= ranges[i + 2][0]:
      return False
  return True