π« School Level Basics
One-line summary: Foundational mathematical and algorithmic building blocks β primes, GCD, palindromes, factorials, digit manipulation. Every DSA practitioner must write these from memory.
Diagramβ
Conceptβ
These problems build your intuition for:
- Digit manipulation: extracting digits via
% 10andMath.floor(n/10) - Primality testing: trial division up to βn
- GCD / LCM: Euclidean algorithm β
gcd(a,b) = gcd(b, a%b) - Palindrome checking: two-pointer or reverse-half technique
- Bit tricks: XOR swap, power-of-two check
Key Algorithmsβ
Euclidean GCDβ
function gcd(a, b) { return b === 0 ? a : gcd(b, a % b); }
function lcm(a, b) { return (a / gcd(a, b)) * b; }
Sieve of Eratosthenesβ
function sieve(n) {
const isPrime = new Array(n + 1).fill(true);
isPrime[0] = isPrime[1] = false;
for (let i = 2; i * i <= n; i++)
if (isPrime[i]) for (let j = i * i; j <= n; j += i) isPrime[j] = false;
return isPrime;
}
Digit Extractionβ
function sumDigits(n) {
let sum = 0;
while (n > 0) { sum += n % 10; n = Math.floor(n / 10); }
return sum;
}
XOR Swap (no temp variable)β
let a = 5, b = 3;
a ^= b; b ^= a; a ^= b; // a=3, b=5
Complexity Summaryβ
| Problem | Time | Space |
|---|---|---|
| Sum 1..N (formula) | O(1) | O(1) |
| Prime check (trial division) | O(βn) | O(1) |
| Sieve of Eratosthenes | O(n log log n) | O(n) |
| Factorial (iterative) | O(n) | O(1) |
| GCD (Euclidean) | O(log min(a,b)) | O(1) |
| Palindrome check | O(n) | O(1) |
Arrays β Key Conceptsβ
Arrays are the most fundamental data structure: a contiguous block of memory with O(1) index access.
| Operation | Time | Notes |
|---|---|---|
| Access by index | O(1) | Random access |
| Search (unsorted) | O(n) | Linear scan |
| Search (sorted) | O(log n) | Binary search |
| Insert at end | O(1) amortized | Dynamic array |
| Insert at index | O(n) | Shift required |
| Delete at index | O(n) | Shift required |
Common pitfalls:
- Off-by-one errors (
<vs<=) - Mutating array while iterating
- Forgetting to handle empty array edge cases
Practice Problemsβ
Related Topicsβ
- Math β deeper number theory
- Bit Manipulation β XOR swap, parity tricks
- Two Pointers β palindrome with two pointers
β Back to Home Β· Β© sparshjaswal