In the usecase [3,5,0,3,4], I receive an error.How did this array fall within the 132 pattern?

68 Views Asked by At

Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].

Return true if there is a 132 pattern in nums, otherwise, return false. `

class Solution 
{
    public boolean find132pattern(int[] nums) 
    {
        int l = 0;
        int r = 2;
        while (r < nums.length)
        {
            int mid=(l+r)/2;
            if (nums[l] < nums[r])
            {
            if (nums[mid]>nums[r]) 
                {
                    return true;
                }
            }

            l++;
            r++;

        }

        return false;
    }
}

This is my solution. if there is a logical error, could you possibly assist me in solving this?

1

There are 1 best solutions below

0
RystaMakesGames On

The issue with your program is that only the very start has to be true. return [value] will end the method, meaning if the start or one part is true, but the rest is false, your program will still return true because it found one part in a "132" format. Rather than returning true in your while loop, you could try returning false:

while (r < nums.length) {
    int mid=(l+r)/2;
    if (nums[l] >= nums[r] && nums[mid] <= nums[r]) {
       return false;
    }           
    l++;
    r++;
}
return true;

This ensures that if any part of the array's condition is false that it will not give a "false positive".

Alternatively you could add a counter like so:

int count = l;
while (r < nums.length) {
    int mid=(l+r)/2;
    if (nums[l] < nums[r] && nums[mid] > nums[r]) {
       count++;       
    }           
    l++;
    r++;
}
if (count == l) {
    return true;
}
return false;

This makes sure the condition was always true. An even more streamlined version of both these methods, however, would likely just be to do this:

int mid=(l+r)/2;
while (r < nums.length && (nums[l] < nums[r] && nums[mid] > nums[r])) {           
    l++;
    r++;
    mid = (l+r)/2;
}
if (r == nums.length) {
    return true;
}
return false;

This immediately checks if the condition is true without the need for an if statement or really anything else.

Results of each:

Are [3, 5, 0, 3, 4] and [6, 8, 7] in a 132 format?
Solution 1: 
    [3, 5, 0, 3, 4]: no :(
    [6, 8, 7]: yes!
Solution 2: 
    [3, 5, 0, 3, 4]: no :(
    [6, 8, 7]: yes!
Solution 3: 
    [3, 5, 0, 3, 4]: no :(
    [6, 8, 7]: yes!

I hope this helped!