Happy Number
Given a positive integer n Return true if n is a happy number, false otherwise A happy number is defined by repeatedly replacing the number by the sum of the squares of its digits until it equals 1 (happy) or loops endlessly in a cycle (not happy) Example: n = 19 => true (1^2 + 9^2 = 82, 8^2 + 2^2 = 68, ..., eventually reaches 1) Example: n = 2 => false (loops in a cycle)
Happy Number rewards a clean two-pointer invariant instead of checking every combination. It's a great warm-up that builds invariant-driven scanning without a ton of moving parts. The trap is moving the wrong pointer and silently skipping the real answer.
Examples
You write
is_happy(n: int)
Example 1
- Input
- n = 19
- returns
- true
Example 2
- Input
- n = 2
- returns
- false
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsTwo Pointers
I reach for it when
- The array is sorted, or you can sort it.
- You need a pair, a triple or a palindrome.
Say this before you type. Say what each pointer means and what a move to the left or right rules out.
All 26 Two Pointers problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.