Few Leetcode lessons

After solving a handful of problems on Leetcode, here are a few tips I learned along the way:

  • For recursion solutions, caching can greatly simplify the code

          from functools import cache
          @cache
          def fibonacci(n):
            ...  
  • To check an optional parameter is missing, do

          if not head:
            ...  
  • If we need to sum over all consecutive sequences of five elements (x1 to x5, x2 to x6, ...), then for speedup we should calculate the first sum of x1 to x5, then subtract x1 and add x6 for second element and so on.

  • Some problems can be easily solved using bit manipulation operators such as

    <<, >>, |, ...

  • To keep track of a number of objects of a given kind, use

    from collections import Counter

  • Instead of looping over elements, use

          all(array)
          any(array) 

  • Swapping variables does not need a temporary variable and can be achieved with

          A, B = B, A

  • Python lists have useful inbuilt functionality, for example

          list.remove('a') # removes first a
          list.count('a')  # returns number of 'a' in the list 
  • Converting int to binary string and back can be done with

          binary = f'{n:b}'
          n = int(binary, 2) 
  • Python has an inbuilt implementation of heap with

          import heapq 

13 Nov 2022