JavaScript solution emphasizing logical clarity


  • 0
    var increasingTriplet = function(nums) {
        let min = nums[0];
        let secondMinUpdatedAfterMin = Infinity;
        for (let val of nums) {
            if (val <= min) {
                min = val;
            } else if (val <= secondMinUpdatedAfterMin) {
                secondMinUpdatedAfterMin = val;
            } else {  // min < secondMinUpdatedAfterMin < val
                return true;
            }
        }
        return false;
    };
    

    This solution has already been posted by others, but I think it's easier to understand with some subtle changes. This particular logic greatly benefits from clear naming.

    Start min off at the first element so that secondMinUpdatedAfterMin is bigger, unlike the case where we start at Infinity. This makes it clear that min is the minimum thus far, and more importantly it's obvious that we are using the the two variables as our respective i and j elements since min < secondMinUpdatedAfterMin.

    Most importantly secondMinUpdatedAfterMin is a better name than bigger or even secondMin because these do not convey when the variable is updated. A name like secondMin is presumed to be the global second minimum so far, which is definitely not the case. For example, nums = [12,8,11,4,6,5,1,9,2,10] stores the following on each iteration:

                              │    │    │    │  i │    │  j │    │  k │    │
    ──────────────────────────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────
     nums                     │ 12 │  8 │ 11 │  4 │  6 │  5 │  1 │  9 │  2 │ 10
    ──────────────────────────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────
     min                      │ 12 │  8 │  8 │  4 │  4 │  4 │  1 │  1 │  - │  -
    ──────────────────────────┼────┼────┼────┼────┼────┼────┼────┼────┼────┼────
     secondMinUpdatedAfterMin │  ∞ │  ∞ │ 11 │ 11 │  6 │  5 │  5 │  5 │  - │  -
    

    The 4th time around secondMinUpdatedAfterMin is 11 but the global second minimum so far is 8 which is the impression given by an ambiguous naming. The shorter secondMinAfterMin is better as well, but it is also ambiguous in that after isn't true in every sense--in the aforementioned iteration 11 comes before 4 in nums.

    Just my opinion, feel free to disagree :).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.