LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Find the Bug · Question 1

Error: hi starts one past the end Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

The program below stops with an error. Which statement correctly describes the problem?

main.py
def search(a, target):
    lo, hi = 0, len(a)
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(search([1, 3, 5, 7], 9))
  • A It prints -1
  • B It loops forever
  • C IndexError: with hi = len(a) and lo <= hi, mid can reach len(a) when the target is larger than every item; use hi = len(a) - 1 Correct
  • D TypeError
Correct Answer: Option C

Keep the bounds consistent: either hi = len(a) - 1 with lo <= hi, or hi = len(a) with lo < hi.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links