educative.io

Find the Closest Number - Solution Doubt

Inside the while loop, check the following condition

    if mid+1 < len(A):
        min_diff_right = abs(A[mid + 1] - target)
    if mid > 0:
        min_diff_left = abs(A[mid - 1] - target)

Since there could be a situation when we don’t update either one of them, shouldn’t we reinitialize min_diff_right and min_diff_left to float(“inf”) inside the while loop in the beginning to make sure there’s no corner case that uses it inadvertently?


Course: Data Structures and Algorithms in Python - AI-Powered Learning for Developers
Lesson: Find the Closest Number - Data Structures and Algorithms in Python