How does insertion sort work, and when is it a good choice?
Simple meaning
You grow a sorted prefix and insert the next element by shifting larger values right.
Open the full page for Why, Steps, Example and Key takeaway.
Panel-ready DSA interview set questions for freshers and experienced developers. Practice at Coding Cadre in Faridabad, or Online from Delhi NCR.
You grow a sorted prefix and insert the next element by shifting larger values right.
Open the full page for Why, Steps, Example and Key takeaway.
Big-O describes how runtime or memory grows as input size n grows, ignoring constants and lower-order terms.
Open the full page for Why, Steps, Example and Key takeaway.
On a sorted array, each step halves the search range, so time is O(log n) and extra space is O(1) iterative or O(log n) recursive.
Open the full page for Why, Steps, Example and Key takeaway.
Multiply independent iteration counts: an n-loop around an n-loop is O(n^2).
Open the full page for Why, Steps, Example and Key takeaway.
Time complexity is how the number of operations grows
Open the full page for Why, Steps, Example and Key takeaway.
The base case is the input that returns immediately without another recursive call, such as n == 0 for factorial.
Open the full page for Why, Steps, Example and Key takeaway.
Recurse on n-1 first, then print n, so the prints happen on the way back
Open the full page for Why, Steps, Example and Key takeaway.
Recursion matches tree and graph DFS, divide-and-conquer, and backtracking because the call stack stores the path.
Open the full page for Why, Steps, Example and Key takeaway.
A power of two has exactly one bit set, so n > 0 and (n & (n - 1)) == 0.
Open the full page for Why, Steps, Example and Key takeaway.
Brian Kernighan's trick repeatedly does n &= n - 1, clearing the lowest set bit until n is zero
Open the full page for Why, Steps, Example and Key takeaway.
Access by index is O(1) because the address is base plus index times size.
Open the full page for Why, Steps, Example and Key takeaway.
Kadane’s algorithm keeps a running best ending here.
Open the full page for Why, Steps, Example and Key takeaway.
O(1) average with a good hash.
Open the full page for Why, Steps, Example and Key takeaway.
Substring is contiguous
Open the full page for Why, Steps, Example and Key takeaway.
Put one array in a hash set and scan the other for hits.
Open the full page for Why, Steps, Example and Key takeaway.
Two pointers from ends moving inward comparing characters.
Open the full page for Why, Steps, Example and Key takeaway.
O(n log n) grows faster by a log factor — sorting is the classic case.
Open the full page for Why, Steps, Example and Key takeaway.