Programming Skills LeetCode Day 1: Solutions

 

Day 1 of LeetCode are

1. Count odd numbers in an interval range:

    If we do not apply trick to this question, then we are going to fail. If we try testing each number one by one, it will take up a lot of memory and runtime. And henceforth, we fail. The trick is simple.

i. Check to find if first number or last number is odd. If that's the case, we can do like this:

            if (low%2 == 1 or high %2 == 1):

                return (high-low)//2 + 1

If you get confused, just take pen and paper and try it yourself.

ii. If the above case is not satisfied:

            else:

                return (high-low)//2   

 Complete Solution:

            class Solution:

          def countOdds(self,low:int, high:int)->int:

              if (low%2 == 1 or high%2 == 1):

                  return (high-low)//2 + 1

               else:

                  return (high-low)//2



2. Average Salary Excluding the Minimum and Maximum Salary

    This is even more easy than previous question as this question does not need any trick. Simply, use built-in functions of python. We can solve this:

sort() will put elements in ascending order. We can pass reverse for descending order like this sort(reverse = True). Rest of our code is self-explanatory. If you got stuck, comment below. I will answer your queries. 

            class Solution:

             def (average(self, salary:List[int]) -> float:

                    salary.sort()

                    salary = salary[1:len(salary)-1]

                    return round(sum(salary)/len(salary,5)

 

Post a Comment

To Top