Predict the output
What does this print?
a, t = [1, 3, 4, 6, 8, 11], 10
lo, hi, steps = 0, len(a) - 1, 0
while a[lo] + a[hi] != t:
steps += 1
if a[lo] + a[hi] < t:
lo += 1
else:
hi -= 1
print(a[lo], a[hi], steps)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 4 6 4
Right: 1+11 too big, 1+8 too small, 3+8 too big, 3+6 too small, then 4+6 hits 10.
Each move discards exactly one value that cannot be in any pair, so four moves are enough here.
Why not the others?
- B 4 6 3. Count the moves again: 3+6 = 9 also needs a move before 4+6.
- C 3 8 2. 3 + 8 is 11, which is too big, so the sweep keeps going.
Steps come from running the Python solution.
Text version
Target 10:
Cells: [1, 3, 4, 6, 8, 11]
- L = 0, R = 5. Sum = 12. 1 + 11 = 12, too big: move R
- L = 0, R = 4. Sum = 9. 1 + 8 = 9, too small: move L
- L = 1, R = 4. Sum = 11. 3 + 8 = 11, too big: move R
- L = 1, R = 3. Sum = 9. 3 + 6 = 9, too small: move L
- L = 2, R = 3. Sum = 10. 4 + 6 = 10: found
Result: true
Target 13:
Cells: [1, 3, 4, 6, 8, 11]
- L = 0, R = 5. Sum = 12. 1 + 11 = 12, too small: move L
- L = 1, R = 5. Sum = 14. 3 + 11 = 14, too big: move R
- L = 1, R = 4. Sum = 11. 3 + 8 = 11, too small: move L
- L = 2, R = 4. Sum = 12. 4 + 8 = 12, too small: move L
- L = 3, R = 4. Sum = 14. 6 + 8 = 14, too big: move R
- L = 3, R = 3. Pointers met: no pair
Result: false