Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Binary search for x in a sorted int array (C++):
Problem: Binary search for x in a sorted int array (C++):
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2; // line 3
if (a[mid] == x) return mid;
if (a[mid] < x) lo = mid; // line 5
else hi = mid - 1;
}
return -1;Which line contains the bug that can cause an infinite loop?- A. Line 3 – (lo + hi) / 2 always loops forever
- B. Line 1 – hi must be n
- C. There is no bug
- D. Line 5 – it must be lo = mid + 1
Correct answer: D. Line 5 – it must be lo = mid + 1
With lo = mid, when hi = lo + 1 and a[lo] < x, mid stays equal to lo forever. (lo + hi) / 2 can overflow only for indices near 2³¹ – worth fixing with lo + (hi − lo)/2, but it is not what causes the loop here. hi = n − 1 matches the inclusive loop condition.
More Coding Interview Problems questions
- Problem: Kadane's algorithm (Java): java int best = 0, cur = 0; // line 1 for (int x : a) { cur = Math.max(x, cur + x); // line 3 best =…
- Problem: BFS shortest path on a grid (Python): python q = deque([start]); dist = {start: 0} while q: u = q.popleft() for v in…
- Problem: Detect whether an undirected graph has a cycle with DFS: python def dfs(u): seen.add(u) for v in adj[u]: if v in seen: return…
- Problem: Climbing-stairs memoisation in Python: python def ways(n, memo={}): if n <= 1: return 1 if n in memo: return memo[n] memo[n] =…
- Problem: Reverse a singly linked list (C++): cpp Node prev = nullptr; while (head) { head->next = prev; // line 3 prev = head; head =…
- Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while…