I just did a HackerRank challenge, but my code kept failing 3 tests, with a timeout error. These tests were probably passing very large arrays as arguments (constraints said the arrays could have as many as 109 elements).
I researched some performance bottlenecks in my code (Array.slice, Math.min and Math.max, getting rid of unnecessary loops, etc) and optimized them all, but these tests were still failing. Is there a better way to approach this problem?
The statement:
Given an integer array space
of length n
, divide it into segments of size x
, find the minimum value of each segment, then return the maximum value of all encountered minima.
Example:
x = 2
space = [8, 2, 4, 6]
segments:
[8, 2]
[2, 4]
[4, 6]
minima: [2, 2, 4]
// Final answer: 4
Can't remember the constraints exactly but it was something like:
1 ≤ x ≤ n
1 ≤ n ≤ 109
1 ≤ space[i] ≤ 109
My code:
function segment(x: number, space: number[]): number {
let left = 0;
let right = x;
let max = 0;
for (let i = 0; i < space.length; i++) {
if (space[right - 1] === undefined) {
break;
}
let localMin = Infinity;
for (let j = left; j < right; j++) {
if (space[j] < localMin) {
localMin = space[j];
}
}
if (localMin > max) {
max = localMin;
}
left++;
right++;
}
return max;
}
console.log(segment(2, [8, 2, 4, 6])); // 4