My solution to a “Daily Coding Problem” that I received in my mail today.
Given an array of numbers and an index
i, return the index of the nearest larger number of the number at index i, where distance is measured in array indices.
For example, given
[4, 1, 3, 5, 6] and index 0, you should return 3.
If two distances to larger numbers are the equal, then return any one of them. If the array at
i doesn’t have a nearest larger integer, then return null.
Here’s my solution in,
oneFortyFour(arr: number[], i: number): number | null {
if(arr == null || arr == undefined) {
return null;
}
if(i >= arr.length) {
return null;
}
let distance: number | null = null;
let noAtIdxI = arr[i];
for(let iter=0;iter < arr.length; iter++) {
if(iter == i) continue;
let valAtIter = arr[iter];
if(valAtIter >= noAtIdxI) {
if(distance == null) {
distance = Math.abs(iter - i);
}
else if(Math.abs(iter - i) < distance) {
distance = iter - i;
}
}
}
return distance;
}
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.
Comments