Mock interview problem: "Altitude deltas" - tim-hr/superprep GitHub Wiki
Setup
- Make a Codestitch pad at codestitch.io.
- If you don't have access privileges, ask Muhammad.
- Paste the problem statement into the Codestitch pad.
- Make sure they know that they can ask questions of the interviewer.
- Make sure they know that this is "open book" -- they look stuff up on the Internet (preferably staying on the MDN site).
Problem statement
/*
You are given an array of integer altitudes along a hiking trail, as well as two indexes into that array. The two indexes represent the start and end of a segment in the array.
Return the sum of the changes for a walk within that segment (i.e., beginning at the start index and ending at the end index). Each integer in the array represents another height on the trail, so "walking" will mean accumulating each change in height into a "sum of the changes".
Note that *increases* in height count double.
For example, with the heights `[1, 2, 3, 1]` and `start=0`, `end=3`, the return value should be 6.
Similarly, with the heights `[5, 3, 6, 7, 2]` and `start=2`, `end=4`, the return value should be 7.
sumAltitudeDeltas([5, 3, 6, 7, 2], 2, 4) --> 7
sumAltitudeDeltas([5, 3, 6, 7, 2], 0, 1) --> 2
sumAltitudeDeltas([5, 3, 6, 7, 2], 0, 4) --> 15
sumAltitudeDeltas([4, 1, 4, 0, 20, 13], 1, 4) --> 50
*/
Notes for interviewer
This isn't a very hard problem (after you parse the description).
This problem a lot harder to do with a reduce.
In part we're testing to see if our interviewee can be pragmatic and use a for-loop first. If they start to go down that path and it gets really hairy, they can hopefully course-correct, especially given a small hint.
Sample answer
Reference pseudocode
function sumAltitudeDeltas(altitudes, start, end) {
// cut the altitudes to just the segment we want
// group the segment into pairs
// e.g., [5, 3, 6, 7] -> [ [ 5, 3 ], [ 3, 6 ], [ 6, 7 ] ]
// calculate the delta between elements of each pair
// sum the deltas
}
Reference implementation
function sumAltitudeDeltas(altitudes, start, end) {
return getPairs(altitudes.slice(start, end + 1))
.map(calculateDelta)
.reduce(sumValues);
}
function getPairs(array) {
var pairs = [];
for (var i = 0; i < array.length - 1; i++) {
pairs.push([array[i], array[i + 1]]);
}
return pairs;
}
function calculateDelta(pair) {
let height1 = pair[0];
let height2 = pair[1];
let delta = Math.abs(height1 - height2);
return (height1 < height2) ? delta * 2 : delta;
}
function sumValues(a, b) {
return a + b;
}
Another implementation of getPairs
An alternate, functional implementation of getPairs could look like this:
function getPairs(array) {
return array.slice(0, -1).reduce(function(pairs, el, index) {
pairs.push([el, array[index + 1]]);
return pairs;
}, []);
}