Proble What to Logic / Common Code Snippet
m Use / Think Approach Methods / Tips
About
Reverse String Iterate str[::-1], s = "hello"\nprint(s[::-1]) # 'olleh'
a string slicing, backward reversed()
loops, built- s or use
in functions slicing
Check if String Compare s == s[::-1] s = "racecar"\nprint(s == s[::-1]) # True
string is comparison string to
palindr its
ome reverse
Find Built-in Use built- max(list), lst =
max/mi functions in or loop min(list) [1,3,2]\nprint(max(lst))\nprint(min(lst))
n in list through
list
Remov Sets, list Convert list(set(lst)), seen lst = [1,2,2,3]\nprint(list(set(lst)))
e comprehens list to set set
duplicat ion or track
es from seen
list elements
Count Dictionary, Map Counter(lst) from collections import Counter\nc =
frequen collections.C element Counter([1,2,2,3])\nprint(c)
cy of ounter →
elemen frequency
ts
Commo Sets Intersecti set1 & set2 a = [1,2,3]; b = [2,3,4]\nprint(set(a) &
n on of sets set(b))
elemen
ts in
two
lists
Check if Sorting Sort and sorted(s1) == s1 = "listen"; s2 =
strings strings, compare sorted(s2), "silent"\nprint(sorted(s1) == sorted(s2))
are frequency or count Counter()
anagra counting character
ms s
Factoria Loops, Multiply Recursive def fact(n): return 1 if n==0 else
l of a recursion from 1 to function or loop n*fact(n-1)\nprint(fact(5))
number n
Fibonac Recursion, Recursivel @lru_cache, from functools import
ci nth memoizatio y or loops lru_cache\n@lru_cache\ndef fib(n):
number n iteratively
compute return n if n<2 else fib(n-1)+fib(n-
nth 2)\nprint(fib(6))
Prime Loops, math Check for i in range(2, def is_prime(n):\n if n<2: return False\n
number divisibility int(n**0.5)+1) for i in range(2,int(n**0.5)+1):\n if
check up to n%i==0: return False\n return
sqrt(n) True\nprint(is_prime(11))
Merge Two Iterate heapq.merge() import
two pointers, both heapq\nprint(list(heapq.merge([1,3,5],[
sorted iteration simultane 2,4,6])))
lists ously
Find Math Use sum n*(n+1)//2 - lst = [1,2,4,5]; n = 5\nprint(n*(n+1)//2 -
missing formula, formula sum(lst) sum(lst))
number XOR or XOR
in 1..n
list
Reverse String Split, ' s = "hello world"\nprint('
words split/join reverse, '.join(sentence.s '.join(s.split()[::-1]))
in a and join plit()[::-1])
sentenc
e
Balance Stack Push Use list as stack def balanced(s):\n stack=[]\n for c in s:\n
d open, if c=='(': stack.append(c)\n elif c==')':\n
parenth pop on if not stack: return False\n stack.pop()\n
eses close, return not stack\nprint(balanced('(()())'))
check check
stack
Second Sorting, Sort or sorted(lst)[-2], lst = [1,4,2,3]; lst.sort(); print(lst[-2])
largest iteration track top loop with two
elemen two vars
t in list
Calculat Euclidean Recursive Recursive def gcd(a,b): return a if b==0 else
e GCD algorithm reduce function gcd(b,a%b)\nprint(gcd(20,8))
until
remainde
r is 0
Queue Stacks Push to Two lists as class Q:\n def __init__(self): self.s1=[];
using one, pop stacks self.s2=[]\n def enq(self,x):
two from self.s1.append(x)\n def deq(self):\n if
stacks other not self.s2:\n while self.s1:\n
self.s2.append(self.s1.pop())\n return
self.s2.pop() if self.s2 else None
Pairs Hash Store target - current def pairs(lst, target):\n seen=set()\n for
with map/dict complem in dict num in lst:\n if target-num in seen:\n
given ents print((num,target-num))\n
sum during seen.add(num)\npairs([1,2,3,4],5)
iteration
Flatten Recursion Recursivel isinstance(el, list) def flatten(lst):\n res=[]\n for el in lst:\n
a y process if isinstance(el,list):
nested sublists res.extend(flatten(el))\n else:
list res.append(el)\n return
res\nprint(flatten([1,[2,[3,4]],5]))
Longest Sliding Expand Use dict to store def lengthOfLongestSubstring(s):\n
substrin window, window, indices seen={}\n left=0\n max_len=0\n for
g w/o two track, right,c in enumerate(s):\n if c in seen
repeat pointers shrink on and seen[c]>=left:\n left=seen[c]+1\n
chars duplicate seen[c]=right\n
max_len=max(max_len,right-left+1)\n
return
max_len\nprint(lengthOfLongestSubstri
ng('abcabcbb'))
Binary Loops, Divide mid = (start + def bin_search(arr,target):\n
search recursion and end)//2 left,right=0,len(arr)-1\n while
conquer left<=right:\n mid=(left+right)//2\n if
in sorted arr[mid]==target: return mid\n elif
list arr[mid]<target: left=mid+1\n else:
right=mid-1\n return -1
Count Loops, Check 'aeiou' in s='hello'\nprint(sum(c in 'aeiou' for c in
vowels membership each c.lower() s.lower()))
in string check character
Find collections.C Count Counter.most_co from collections import
the ounter and find mmon(1) Counter\nc=Counter([1,1,2,3,3,3])\nprin
mode max t(c.most_common(1))
(most
frequen
t
elemen
t)
Check if Loop, all() Compare all(lst[i] <= lst=[1,2,3]\nprint(all(lst[i]<=lst[i+1] for i
list is function pairs of lst[i+1]) in range(len(lst)-1)))
sorted elements
Rotate Slicing, Use lst[-k:] + lst[:-k] lst=[1,2,3,4,5]; k=2\nprint(lst[-k:] + lst[:-
array by modulo slicing k])
k and join
positio
ns
Intersec Sets Use set.intersection( sets=[set([1,2,3]), set([2,3,4]),
tion of set.inters *sets) set([3,4,5])]\nprint(set.intersection(*set
multipl ection s))
e lists
Missing Sets Differenc set(full) - full=[1,2,3,4]; part=[2,3]\nprint(set(full)-
elemen e of sets set(part) set(part))
ts
betwee
n two
lists
Implem Functions, Wrap Wrapper inside def deco(func):\n def wrapper():\n
ent a closures function decorator print('Before')\n func()\n print('After')\n
decorat behavior return wrapper\n@deco\ndef f():
or print('Hello')\nf()