Interview - Find magnitude pole in an array

前端 未结 8 2402
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:52

Magnitude Pole: An element in an array whose left hand side elements are lesser than or equal to it and whose right hand side element are greater than or equal to it.

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 16:30

    Your logic seems perfectly correct (didn't check the implementation, though) and can be implemented to give an O(n) time algorithm! Nice job thinking in terms of sets.

    Your right set can be implemented as a stack which supports a min, and the left set can be implemented as a stack which supports a max and this gives an O(n) time algorithm.

    Having a stack which supports max/min is a well known interview question and can be done so each operation (push/pop/min/max is O(1)).

    To use this for your logic, the pseudo code will look something like this

    foreach elem in a[n-1 to 0]
        right_set.push(elem)
    
    while (right_set.has_elements()) {
       candidate = right_set.pop();
       if (left_set.has_elements() && left_set.max() <= candidate <= right_set.min()) {
           break;
       } else if (!left.has_elements() && candidate <= right_set.min() {
            break;
       }
       left_set.push(candidate);
    }
    
    return candidate
    

提交回复
热议问题