End of the Trip and Today's POTD

It's 8th of August and I have returned from a 12 days long trip or vacay whatever, it was extremely good and quite refreshing and was a good experience overall, although I feel that I have an aversion for temples maybe, cause they never excite me, it's the nature and the open places that I seek. 

Well, I have missed around 12 potds bcz of the trip, but it's fine, maybe I'll cover them in some free time, but today's GFG POTD was based on somewhat previous problems of the month of july I guess, there was some problem where we had to see that how many pairs of numbers sum up to 3 in the array, and the t. complexity required there too was O(n logn), and that time I wasn't aware about this 2 pointer approach, but for this problem I figured out what I have to do in about 10 mins, it just came to my mind, by looking at the TC required that I have to sort this array, and then the question was... what after sorting? What am I gonna achieve? And the answer just was quite clear after the fog cleared, it was to use the previous and the interesting 2 pointer approach to get the result.

I think the code should be self explanatory and if practiced or tinkered with pen n paper will be all easy to grasp. 

Code:-

class Solution:
    def countFractions(self, n, numerator, denominator):
        # Your code here
        # 0.333,0.1,3.858,0.9,0.4
       
        # Sorted:-
        # 1/10 , 3/9   , 2/5  , 12/18 , 81/90  
        # 0.1  , 0.333 , 0.4  , 0.666 , 0.9
        i,j=0,n-1
        count=0
       
        data=[ numerator[i]/denominator[i] for i in range(n) ]
       
       
        data.sort()
        # print(data)
        while(i<j):
            if(data[i]+data[j]<1):
                i+=1
            elif(data[i]+data[j]>1):
                j-=1
            else:
                # print(data[i],data[j])
                # Just considering all the vals that satisfy the condition with the
                # ith value, and then when are done with this ith val then just
                # incrementing the value of i, to consider new fresh cases
                prev_j_val=j
               
                while(data[i]+data[j]==1 and i<j):
                    count+=1
                    j-=1
                   
                j=prev_j_val
                i+=1
               
                # The below code is logically incorrect for test cases like:
                # 0.1,0.1,0.9,0.9,0.9
                # basically in such cases the below logic will consider first 0.1,
                # with all the 0.9s but the second 0.1, will be only considered
              # alongwith
                # the first 0.9, which will give wrong output eventually
               
                # count+=1
                # if(data[i]+data[j-1]>=1):
                #     j-=1
                # else:
                #     i+=1
        return count

Comments

Popular Posts