My solution to a “Daily Coding Problem” that I received in my mail today.

Given a list of numbers L, implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j).

For example, given L = [1, 2, 3, 4, 5]sum(1, 3) should return sum([2, 3]), which is 5.

You can assume that you can do some pre-processing. sum() should be optimized over the pre-processing step.

Here’s my solution in Typescript,

oneFortyNine(l: number[], i: number,j: number): number {
    if(l == null) {
        return 0;
    }
    if(l.length == 0 || i >= l.length || j >= l.length || j < i) {
        return 0;
    }
    //ok, we aren't avoid checking for i and j being zero
    //this code also assumes i < j
    if(i == (j - 1)) {  
        return l[i];
    }
    return l[i] + this.oneFortyNine(l, i+1, j);
}

I actually, don’t understand the pre-processing part of this code? As in pre-processing how? Also, this problem was labelled as “hard”, so while the tests give the right solution, I wonder do I have the right solution? This was quite easy, and if I had done it iteratively, it would be even easier.

Like the blog? Subscribe for updates

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. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *