-3

I am trying to increase the efficiency of a function. It is currently quadratic and I would like to make it logarithmic.

The third to last line of the current function is confusing me somewhat as well and I would like some clarification.

function solution(arr){
   let result = 0
    for ( let i = 0; i < arr.length; i++)
        for (let j = 0; j < arr.length; j++)
            if (arr[i] == arr[j])
                result = Math.max(result, Math.abs(i - j));
         return result;
 }

How do I solve this problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
aluko17
  • 21
  • 3
  • 1
    Welcome to Stackoverflow! Please remember that SO is not a general help forum, and if you have code that already works, but you want to improve/optimize it, SO is not the right place to ask. Have a look at https://codereview.stackexchange.com if you want help improving something that works, rather than asking about how to fix code that doesn't (or start trying to rewrite this code yourself, and then once you get stuck because the code's not doing what you thought it should be doing, ask about that here) – Mike 'Pomax' Kamermans May 01 '19 at 15:41
  • This can be solved in linear time. `let j = i + 1` does increase the performance greatly already, for linear time you need a Map. – Jonas Wilms May 01 '19 at 15:41
  • What exaxtly confuses you? – Jonas Wilms May 01 '19 at 15:43

2 Answers2

1

At least, you could change the indices for looping and omit self checking and to check the same pairs again.

function solution(arr){
    let result = 0
    for (let i = 0; i < arr.length - 1; i++)
        for (let j = i; j < arr.length; j++)
            if (arr[i] === arr[j])
                result = Math.max(result, Math.abs(i - j));
    return result;
}

The shortest approach is O(n) by taking an hash table for storing the first found index for a value.

function solution(array) {
    var hash = {};
    return array.reduce(
        (m, v, i) => Math.max(m, i - (hash[v] = v in hash ? hash[v] : i)),
        0
    );
}

var array = [1, 3, 4, 5, 1, 3, 4, 5, 6, 2, 3];

console.log(solution(array));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

In the above function, the goal is to find the maximum number from array. Now the meaning of third to last line which is result = Math.max(result, Math.abs(i - j)); , I will break it into two parts to explain here,

First of all, Math.abs(i-j) will be executed and provide the absolute value from the difference between i and j.

After this, the outer function Math.max() method will be called which will provide you the maximum value between result and absolute value obtained from first step. Now the maximum value will be store in result. This is how the function is working.

Now this statement is conditional based, which means it will only execute if arr[i]==arr[j].

I hope it cleared the work flow of this program.

Pradhumn Sharma
  • 1,663
  • 2
  • 10
  • 19