Python Tricks for LeetCode & Competitive
Programming
String Tricks
- s[::-1] → Reverse string
- "".join(reversed(s)) → Reverse string (function way)
- [Link]() → Split by whitespace into words
- " ".join(words) → Join list of words with spaces
- [Link](), [Link]() → Check if string is numeric/alphabetic
- [Link](), [Link]() → Lowercase / Uppercase
- [Link]("a") → Count occurrences of 'a'
List Tricks
- arr[::-1] → Reverse list
- sum(arr) → Sum elements
- max(arr), min(arr) → Largest, smallest
- sorted(arr) → New sorted list
- [Link]() → Sort in place
- sorted(arr, reverse=True) → Sort descending
- [i for i in arr if i%2==0] → Even numbers list comprehension
Set & Dict Tricks
- set(arr) → Unique elements
- list(set(arr)) → Deduplicate list
- dict(zip(keys, values)) → Make dict from two lists
- {x: [Link](x) for x in arr} → Frequency count
Loop Tricks
- for idx, val in enumerate(arr) → Index & value loop
- for a, b in zip(list1, list2) → Loop two lists in parallel
- for i in range(len(arr)-1, -1, -1) → Reverse index loop
Math / Searching
- abs(x) → Absolute value
- divmod(a, b) → Quotient and remainder
- any(arr) → True if any element is True
- all(arr) → True if all elements are True
LeetCode Favorites
- from collections import Counter
- Counter(arr) → Frequency dictionary
- max(Counter(arr), key=Counter(arr).get) → Most common element
- from itertools import product, permutations, combinations
- list(product([1,2], [3,4])) → Cartesian product