These problem-solving tricks are distilled from practical C, Java, and Python usage. They help you write shorter, faster, and safer code in interviews, contests, and projects: from operator shortcuts and bitwise hacks to conditional and loop patterns.
Core operator & bitwise tricks
Master a small set of operator and bitwise patterns; you will reuse them across many coding questions (parity, powers of 2, toggling bits, counting bits, and swaps).
Operator & bit tricks
| Trick | C | Java | Python |
|---|---|---|---|
| Integer division | 5 / 2 = 2 |
5 / 2 = 2 (int / int) |
5 / 2 = 2.5, 5 // 2 = 2 |
| Increment | i++, ++i |
i++, ++i |
i += 1 (no ++) |
| Exponent | pow(2, 3) (math.h) |
Math.pow(2, 3) |
2 ** 3 or pow(2, 3) |
| String concat | strcat(s1, s2) |
s1 + s2 |
s1 + s2 or f\"{s1}{s2}\" |
| Null / None check | Pointer != NULL |
if (obj == null) |
if obj is None |
-
Even / odd and power-of-2 checks
Use bitwise instead of extra division
Check odd/even with
x & 1(C/Java/Python). Check power of 2 withn & (n - 1) == 0(andn != 0)—a classic trick for many bit problems. -
Toggle, set, and clear k-th bit
Bit masks for targeted changes
Toggle:
x ^= (1 << k); set:x |= (1 << k); clear:x &= ~(1 << k). These appear in subset, mask DP, and permissions-style problems. -
Fast multiply/divide and modulo by 2ⁿ
Replace heavy operations with shifts & masks
Multiply/divide by powers of 2 using shifts:
x << n,x >> n. For modulo 2ⁿ, usex & ((1 << n) - 1), useful in hashing and cyclic buffers. -
Count set bits quickly
Use built-ins or Kernighan’s algorithm
In C, use Kernighan’s loop (
while (n) { n &= (n - 1); }); in Java useInteger.bitCount(n); in Python usebin(n).count('1'). This pattern appears in DP-on-subsets and mask problems. -
Swap values safely
Prefer readable swaps
Classic XOR swap (
a ^= b; b ^= a; a ^= b;) is good to know conceptually, but preferswap(a, b)in C++ ora, b = b, ain Python for clarity and fewer bugs.
Conditional & boolean tricks
Good conditions make code easier to read and safer—especially around edge cases, null checks, and branching.
Conditional patterns
| Pattern | C | Java | Python |
|---|---|---|---|
| Simple if | if (cond) { ... } |
if (cond) { ... } |
if cond: |
| if–else | if (c) { ... } else { ... } |
if (c) { ... } else { ... } |
if cond: ... else: ... |
| else-if ladder | if (...) { } else if (...) { } else { } |
same as C | if ...: elif ...: else: |
| Nested if | if (a) { if (b) { ... } } |
if (a) { if (b) { ... } } |
if a:
if b: ... |
| Switch / match | switch (x) { case 1: ... } |
switch (x) { case 1: ... } (Java 14+) |
match x:
case 1: ... (Py 3.10+) |
| Ternary operator | res = cond ? a : b; |
res = cond ? a : b; |
res = a if cond else b |
| Range / BETWEEN | if (x >= 10 && x <= 20) |
if (x >= 10 && x <= 20) |
if 10 <= x <= 20: |
| Char uppercase check | if (ch >= 'A' && ch <= 'Z') |
if (Character.isUpperCase(ch)) |
if ch.isupper(): |
| String equality | strcmp(s1, s2) == 0 |
\"Yes\".equals(str) |
if str == \"Yes\": |
-
Short-circuit AND / OR
Protect expensive calls and division
Use
if (a != 0 && b/a > 2)(C/Java) orif a != 0 and b/a > 2:(Python) so the second part runs only when safe. This avoids divide-by-zero and unnecessary function calls. -
Range checks & chained comparison
Express “between” conditions cleanly
In C/Java, write
if (x >= 10 && x <= 20). In Python, preferif 10 <= x <= 20:for readability. -
Ternary expressions for simple branches
One-line min/max and flags
Example:
res = (a > b) ? a : b;in C/Java orres = a if a > b else bin Python. Use ternary only for simple expressions—otherwise keep a fullif-else. -
Use early returns to reduce nesting
Handle edge cases first
Instead of deep nesting, check errors or trivial cases at the top of a function (
if (n == 0) return 0;) so the main logic stays flat and easier to debug. -
String and null checks
Use the right comparison
In Java, compare strings with
.equals()and always guard objects withif (obj == null). In Python, useis Nonefor identity; in C, remember that non-zero is true.
Loop patterns & templates
Loop structure often decides whether a solution is clean and efficient—know the standard templates well.
Loop tricks
| Loop type | C | Java | Python |
|---|---|---|---|
| for loop | for (int i = 0; i < n; i++) |
for (int i = 0; i < n; i++) |
for i in range(n): |
| while loop | while (cond) { ... } |
while (cond) { ... } |
while cond: |
| do–while loop | do { ... } while (cond); |
do { ... } while (cond); |
No direct; use while True: + break |
| fixed range | for (i = l; i <= r; ++i) |
for (int i = l; i <= r; i++) |
for i in range(l, r+1): |
| reverse loop | for (i = n-1; i >= 0; --i) |
for (int i = n-1; i >= 0; i--) |
for i in range(n-1, -1, -1): |
-
Pick the right loop for the job
for: known count, while: unknown count
Use
for (int i = 0; i < n; ++i)(orfor i in range(n)) when the iteration count is known; usewhile (cond)when you loop until a condition breaks (input-driven, pointer movement). -
Sentinel and do-while style loops
When the body must run at least once
In C/Java,
do { ... } while (cond);guarantees one run. In Python, emulate withwhile True:+breakonce the condition fails. -
Two-pointer & sliding window templates
Efficient array/string traversal
Many array/string problems reduce to two indices (
i,j) and a while loop adjusting them based on constraints (sum, length, distinct elements). Reuse a standard template instead of reinventing. - Loop & condition fusion Stop early when answer is found Combine searching and checks in one loop; break as soon as the answer is known. This often turns O(n·k) patterns into O(n).