Oneliners
A brilliant repository of fantastic, killer one-liners
Install / Use
/learn @joric/OnelinersREADME
Oneliners
Just FYI, this isn't just README.md, it's also more than a thousand solutions in the repository. There's also stats.
- If you find a shorter solution (that also passes online tests, as is no MLE, no TLE), post it to the issues section.
Why Python
Python code is almost always shorter than code in other languages (there's no Perl on Leetcode). Maybe Scala or Ruby can beat it sometimes because they don't need a return statement. Even C++ is sometimes shorter than Python - well, in one particular case it's shorter by one character:
- https://leetcode.com/problems/k-th-symbol-in-grammar/
Python
return(k-1).bit_count()&1
C++
return popcount(k-1u)&1;
Note that u and ; are mandatory here. If I find a shorter solution in other language I usually add it in comments.
Leetcode-specific
Leetcode imports modules as wildcards, so you don't have to specify module names. There are some exceptions:
- Single
bisect()without a prefix triggersobject is not callable, usebisect.bisect()orbisect_left(). - You have to specify
re.subbecausesubwithout a prefix isoperator.sub. - Default
powis__builtins__['pow'](supports up to 3 arguments, including the modulus), notmath.pow.
For example, Leetcode header has import * from math, so we use comb() instead of math.comb():
- https://leetcode.com/problems/unique-paths
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return comb(m+n-2, n-1)
You can also use __import__('module').func for unlisted modules (namely, numpy, scipy, and sortedcontainers).
- https://leetcode.com/problems/check-if-it-is-a-straight-line
class Solution:
def checkStraightLine(self, p):
return __import__('numpy').linalg.matrix_rank([[1]+x for x in p])<3
Sometimes you can save on casting of the return type, e.g. Leetcode autoconverted keys and mixed types to lists.
- https://leetcode.com/problems/top-k-frequent-elements
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return dict(Counter(nums).most_common(k))
It also automatically evaluated generators (stopped worked in Aug 2023, expected return type integer[]):
- https://leetcode.com/problems/counting-bits
class Solution:
def countBits(self, n: int) -> List[int]:
return map(int.bit_count,range(n+1))
You can also return linked list of values as ListNode('a,b,...'). This one is really specific, but sometimes useful.
- https://leetcode.com/problems/add-two-numbers
class Solution:
def addTwoNumbers(self, a: Optional[ListNode], b: Optional[ListNode]) -> Optional[ListNode]:
f=lambda n:n and n.val+10*f(n.next)or 0;return ListNode(','.join([*str(f(a)+f(b))][::-1]))
Leetcode also has serialize and deserialize functions for lists and trees:
- https://leetcode.com/problems/reverse-linked-list
class Solution:
def reverseList(self, h: Optional[ListNode]) -> Optional[ListNode]:
return h and h.deserialize(str(eval(h.serialize(h))[::-1]))
There is also has_sycle function:
- https://leetcode.com/problems/linked-list-cycle
class Solution:
def hasCycle (self, h: Optional[ListNode]) -> bool:
return ListNode.has_cycle(h)
There are also _*_node_to_array and _array_to_*_node functions:
- https://leetcode.com/problems/palindrome-linked-list
class Solution:
def isPalindrome(self, h: ListNode) -> bool:
return(s:=type(h)._list_node_to_array(h))==s[::-1]
- https://leetcode.com/problems/sort-list
class Solution:
def sortList(self, h: Optional[ListNode]) -> Optional[ListNode]:
t=ListNode;return t._array_to_list_node(sorted(t._list_node_to_array(h)))
class Solution:
def sortList(self, h: Optional[ListNode]) -> Optional[ListNode]:
t=ListNode;return t.deserialize(str(sorted(eval(t.serialize(h)))))
You can also dump the entire preprocessed solution file to check all the imports for yourself (see gist):
with open(__file__, 'rt') as f: print(f.read())
The solution driver code writes all results to the user.out file, so we can use it like this:
- https://leetcode.com/problems/two-sum
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
from zlib import decompress
from base64 import b64decode
open('user.out', 'wb').write(decompress(b64decode('eJzdkMEVwCAIQ++dggFyEKi2zuLr/mtItZb63KAc\
kpfwuVAYFK6tCIjNPH1KncodJMuBTqWTYUGe89hNX1Kd/K2Nh1iM3mYbkMlpIaFrvvcCaVwCH+YB3FSHVu5xXDc='))),exit(0)
There is no approved method to get all the test cases for problems in LeetCode. You can, however, leverage the fact that LeetCode reveals the test case that causes your code to fail. The solution above is not very reliable, because tests and environment may change, but it's pretty fast.
- https://leetcode.com/discuss/feedback/4643730/a-python-solution-that-contain-malicious-payload-in-your-website
You can explore the sandbox using shell commands, e.g. (see gist):
import subprocess
print(subprocess.run(["ls", "-la", "/"]))
You can also set your own execution time using atexit:
- https://leetcode.com/discuss/post/6269419/0ms-bug-leetcode-by-phamvietanhvietnames-tuj2/
__import__('atexit').register(lambda: open("display_runtime.txt", "w").write("0")) # 0..2147483647
See https://github.com/LeetCode-Feedback/LeetCode-Feedback/issues/25646 (we have decided not to allocate development resources to fixing it at this time.)
Minus-two-liners
Some leetcode problems may be solved at the function declaration level.
- https://leetcode.com/problems/search-insert-position
class Solution:searchInsert=bisect_left
- https://leetcode.com/problems/permutations
class Solution:permute=permutations
- https://leetcode.com/problems/sort-an-array
class Solution:sortArray=sorted
- https://leetcode.com/problems/bulb-switcher
class Solution:bulbSwitch=isqrt
- https://leetcode.com/problems/search-in-rotated-sorted-array-ii
class Solution:search=contains
- https://leetcode.com/problems/powx-n
class Solution:myPow=pow
Note that it only works for the built-in functions, they can omit self parameter.
It's a built-in CPython feature:
- https://stackoverflow.com/questions/10729909/convert-builtin-function-type-to-method-type-in-python-3
You cannot use your own function like that, without skipping the first argument.
- https://leetcode.com/problems/reverse-words-in-a-string-iii
class Solution:reverseWords=lambda _,s:' '.join(w[::-1]for w in s.split())
It's not necessarily shorter, because lambdas can't use semicolons.
In some cases you don't even have to write "class Solution:", e.g:
- https://leetcode.com/problems/serialize-and-deserialize-binary-tree
Codec=TreeNode
Shortest
Let's consider function declaration is zero lines.
- https://leetcode.com/problems/account-balance-after-rounded-purchase
class Solution:
def accountBalanceAfterPurchase(self, x: int) -> int:
return(104-x)//10*10
- https://leetcode.com/problems/majority-element
class Solution:
def majorityElement(self, n: List[int]) -> int:
return mode(n)
- https://leetcode.com/problems/alice-and-bob-playing-flower-game
class Solution:
def flowerGame(self, n: int, m: int) -> int:
return m*n//2
- https://leetcode.com/problems/count-of-matches-in-tournament
class Solution:
def numberOfMatches(self, n: int) -> int:
return~-n
- https://leetcode.com/problems/stone-game
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
return 1
You can also write:
class Solution:stoneGame=truth
- https://leetcode.com/problems/strictly-palindromic-number
class Solution:
def isStrictlyPalindromic(self, n: int) -> bool:
0
This is 1-symbol solution. Notice no return operator here, can be pass, as function returns None. You can also do:
class Solution:isStrictlyPalindromic=not_
Lambdas
Fictitious (anonymous) lambdas may be nested. E.g. you can use lambdas as parameters:
(lambda a,b,c: code)(a,b,c)becomes(lambda a,b,c: code)(lambda a: code, lamda b: code, lambda c: code)
You can't unpack lambda tuples in Python 3 since PEP 3113, however, if your lambda is flat, there is an upgrade path:
lambda (x, y): x + yin Python 2 becomeslambda xy:(lambda x,y: x+y)(*xy)in Python 3.
You can also unpack multiple tuples as lambda xy,ab:(lambda x,y,a,b: x+y+a+b)(*(xy+ab)).
- https://leetcode.com/problems/count-vowels-permutation
class Solution:
def countVowelPermutation(self, n: int) -> int:
return sum(reduce(lambda x,_:(lambda a,e,i,o,u:(e+i+u,a+i,e+o,i,i+o))(*x),[0]*(n-1),[1]*5))
%(10**9+7)
Sometimes you can unpack tuples with starmap:
- https://leetcode.com/problems/length-of-longest-fibonacci-subsequence
class Solution:
def lenLongestFibSubseq(self, n: List[int]) -> int:
s={*n};return(0,t:=max(starmap(f:=lambda a,b,c=2:s&{a+b}and f(b,a+b,c+1)or c,
combinations(n,2))))[t>
Related Skills
node-connect
349.2kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
claude-opus-4-5-migration
109.5kMigrate prompts and code from Claude Sonnet 4.0, Sonnet 4.5, or Opus 4.1 to Opus 4.5
frontend-design
109.5kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
model-usage
349.2kUse CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost data from codexbar, or when you need a scriptable per-model summary from codexbar cost JSON.
