Compilation of interview questions 1
I was reading Cracking the Coding Interview. Some of its 150 questions are excellent, and my submissions are here. Here are my notes:
5.3 Closest Numbers
Given a positive integer, find the two closest numbers with the same number of
1s in their binary representation—one slightly larger and one slightly smaller.
For the slightly larger number, change the rightmost suitable 0 to 1, then move the remaining 1s as far left as possible. Scan past zeroes, then ones, find the next zero, and turn it into one.
For the slightly smaller number, change the rightmost suitable 1 to 0, then move the remaining 1s as far right as possible. Scan past ones, then zeroes, find the next one, and turn it into zero.
1 | class CloseNumber |
5.7 Draw a Horizontal Line
A monochrome screen is stored in a one-dimensional array, where each element represents eight consecutive pixels. Implement a function that colors pixels $x$ through $y$ (indexed from zero) as efficiently as possible.
Given the screen array (each element represents eight consecutive pixels, whose left-to-right positions correspond to its binary bits from low to high) and integers
xandyas described above, return the recolored screen array. The input is valid.
There are quite a few implementation traps, so it is rather fiddly.
1 | class Render |
9.3 Magic Index (1)
In an array $A[0..n-1]$, a magic index satisfies $A[i]=i$. Given a strictly increasing array with distinct values, determine whether a magic index exists in better than $O(n)$ time.
Given an
intarrayAand its sizen, return aboolindicating whether it contains a magic index.
With distinct values, compare A[mid] with mid and binary-search directly.
1 | class MagicIndex { |
Magic Index (2)
In an array $A[0..n-1]$, a magic index satisfies $A[i]=i$. Given a nondecreasing array whose values may repeat, determine whether a magic index exists in better than $O(n)$ time.
Given an
intarrayAand its sizen, return aboolindicating whether it contains a magic index.
When values may repeat, a single binary-search decision is no longer enough. Recursively search the left and right halves, skipping values where possible; see the code for the details.
1 | class MagicIndex { |
9.10 Stack of Boxes
Given boxes with width $w_i$, depth $d_i$, and height $h_i$, stack them so that each upper box is narrower and shorter than the box below it. Find the greatest possible total stack height.
Given three
intarraysw,l, andhfor each box’s width, length, and height, and the number of boxesn, return the maximum stack height. $n \le 500$.
Use the same DP idea as longest increasing subsequence, after an initial bubble sort.
1 | class Box |