Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-053

Floor and Ceil in Sorted Array

Problem

Find the floor and ceiling of target in a sorted list.

The floor is the greatest value less than or equal to target and the ceiling is the smallest value greater than or equal to target. Use binary search, recording candidate floors while moving right and candidate ceilings while moving left.

Return [floor, ceiling], where either entry is None when it does not exist.

Hint

Every smaller midpoint is a floor candidate; every larger one is a ceiling candidate.

Test cases

case 1
in: [[1,3,5,7],4]
expected: [3,5]
case 2
in: [[1,3,5,7],5]
expected: [5,5]
case 3
in: [[2,4],1]
expected: [null,2]
case 4
in: [[2,4],9]
expected: [4,null]
case 5
in: [[],3]
expected: [null,null]
Starter codePython
def floor_ceil(nums, target):
    # Your code here
    pass

5 test cases · run your code against them in the editor