Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: The function below should return the integer square root ⌊√x⌋.
Problem: The function below should return the integer square root ⌊√x⌋.
static int isqrt(int x) {
int lo = 0, hi = x, ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if ((long) mid * mid <= x) { ans = mid; lo = mid + 1; }
else hi = mid - 1;
}
return ans;
}
// isqrt(26) + " " + isqrt(1) + " " + isqrt(2147395600)What does the commented expression evaluate to?- A. 5 1 46340
- B. 5 1 46341
- C. 6 1 46340
- D. 5 0 46340
Correct answer: A. 5 1 46340
Keep the last mid whose square fits. 5² = 25 ≤ 26 < 36. 2147395600 = 46340² exactly. The (long) cast matters: mid * mid in int overflows for mid near 46341 and the search would go wrong. O(log x).
More Coding Interview Problems questions
- Problem: In an array where every element appears twice except one, and pairs sit next to each other, the array is sorted. Find the single…
- Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index. python def peak(a)…
- Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)). python def kth(a, b, k): if…
- Problem: Reverse a singly linked list of order IDs. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt def…
- Problem: Return the middle node of a linked list (the second middle when the length is even). python class Node: def init(self, v…
- Problem: Remove the k-th node from the end of a list in one pass. python class Node: def init(self, v, nxt=None): self.v, self.next = v…