Some logic for finding nearest element