Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

Solution: Ceiling of a Number

Problem Statement

Given an array of numbers sorted in an ascending order, find the ceiling of a given number ‘key’. The ceiling of the ‘key’ will be the smallest element in the given array greater than or equal to the ‘key’.

Write a function to return the index of the ceiling of the ‘key’. If there isn’t any ceiling return -1.

Example 1:

Input: [4, 6, 10], key = 6
Output: 1
Explanation: The smallest number greater than or equal to '6' is '6' having index '1'.

Example 2:

Input: [1, 3, 8, 10, 15], key = 12
Output: 4

.....

.....

.....

Like the course? Get enrolled and start learning!
D

d.psawyer

· 3 years ago

Testcase:

[1, 1, 1, 1, 1] 1

Test case expected result: 2

Correct result: 0

The test cases claim 2 is the correct result when the correct answer is clearly 0

Show 1 reply
Daniel Szatmari

Daniel Szatmari

· 3 years ago

My code failed on a test case that I think is incorrect.

Given: [1, 1, 1, 1, 1] 1

The result should be 0 whereas the test expects 2. which makes no sense.

J

JC Denton

· 5 years ago

Are repeated integers meant to be handed with this solution? For example, for arguments: ([4, 6, 6, 6, 10], 6)

The result is 2. Reading the prompt it is unclear if this is sufficient or if the answer should be 1 in this case.

Show 1 reply
M

Mikhail Putilov

· 3 years ago

Hi,

Could somebody extend the explanation about it? I think that's pretty important but I don't think that I understand.

I

Ivy

· 4 years ago

Would it be correct in the floor solution to return either end or mid outside the loop? Since integer division "rounds down" so end and mid should always be equivalent by that point.

Renat Zamaletdinov

Renat Zamaletdinov

· 2 years ago

[1, 1, 1, 1, 1] 1

Show 1 reply
Tecson Gacrama

Tecson Gacrama

· 7 months ago

This test case needs to be added:

arr = [1, 3, 5, 7, 9]

key = 4

otherwise this code passes:

class Solution:

def searchCeilingOfANumber(self, arr, key):

if not arr:

return -1

start = 0

end = len(arr)-1

while start <= end:

mid = start + (end-start) // 2

if arr[mid] == key:

return mid

elif arr[mid] < key:

start = mid + 1

else:

end = mid - 1

if arr[mid] > key:

return mid

return -1