Data Structures & AlgorithmsModerateProduct Company SDE · binary search warm-up
Problem: What is the integer floor of the square root of 10^12? Use binary search.
Problem: What is the integer floor of the square root of 10^12? Use binary search.
lo, hi = 0, 10 ** 12
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * mid <= 10 ** 12:
lo = mid
else:
hi = mid - 1
print(lo)What is printed?- A. 999999
- B. 1000000
- C. 1000001
- D. 10000000
Correct answer: B. 1000000
(10^6)^2 = 10^12 exactly, so the floor square root is 10^6. The mid value must be rounded up to avoid an infinite loop.
More Coding Interview Problems questions
- Problem: Split [7, 2, 5, 10, 8] into 2 contiguous parts to minimise the largest part sum. What is the answer? Run the brute-force code…
- Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code. python from collections…
- Problem: How many distinct substrings of length 2 does 'abcabc' contain? Run the code. python s = 'abcabc' print(len({s[i:i + 2] for i in…
- Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code. python s = ')()())'…
- Problem: What is the value of the reverse Polish expression '2 1 + 3 '? Run the stack code. python tokens = '2 1 + 3 '.split() st = [] for…
- Problem: What is the maximum matching size in the bipartite graph with left vertices {0,1,2}, right vertices {0,1,2} and edges (0,0)…