334. Increasing Triplet Subsequence

Medium
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k 
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:
Input: [5,4,3,2,1]
Output: false

Solution:
At each index, we can maintain the smallest value we have got so far and second smallest after smallest index. now if we reach a index whose value is larger than smaller and smallest value. then we found our solution.

test case 2  3 1 4
in result, smallest is 1, secSmallest is 3. the correct answer is 2 3 4. need to get smallest in another loop.

5 4 3 2 1
it always meet n <= smallest, it won't go to the break branch.

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int smallest = Integer.MAX_VALUE, secSmallest = Integer.MAX_VALUE;
        int i = 0;
        for(; i < nums.length; i++){
            int n = nums[i];
            if(n <= smallest){
                smallest = n;
            }else if(n <= secSmallest){
                secSmallest = n;
            }else{
                break;
            }
        }
        if(i == nums.length) return false;
        return true;
    }
}



Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal