Quick Recipes for Problem Solving
CONTENTS
Snippets
Snippets
Data Structures
- Array: Flattening
- Array: Consecutive Combo
- Array: Continuous Subsegment Counts
- Binary Tree: Basics & Traversals
- Binary Tree: Check if Left and Right subtrees are Mirror Images / Symmetric
- Binary Tree: LCA (Basic Recursion)
- DisjointSet Union
- Hashmap: Merging Hashmaps
- Hashmap: Sort
- Hashmap: Tuple to Hashmap
- Hashmap: Generic Stuff
- LinkedList: SLL
- MultiMap
- MultiSet
- OrderedSet
- Range Query: Prefix Sum
- Range Query: FenwickTree
- Range Query: Segment Tree (Min/Max/Sum)
- Range Query: Segment Tree (Offset)
- Trie: Template1
- Trie: Template2
Basics
Graphs
- Check Bi-Partite
- Check if Cycle Exists
- Check Cycle without recursion - Brent's Algorithm
- Check if we can visit all nodes (DFS)
- Count number of connected components in an undirected graph
- Djikstra (Using Heap)
- Find Shortest Path from Source to Target
- Find Path b/w Source & Target - Single Parent
- Find minimum vertices to reach all nodes
- Topological Sort
- BFS & DFS
Strings
- Check Palindrome
- Change to Lower
- Check if s is subsequence of t
- Generate all substrings O(n^2)
- Hashing (Rolling Hash)
- KMP
- Longest Common Substring (LCS)
- Longest Increasing Subsequence (LIS)
- Rabin Karp
- Rolling Hash - Find duplicates in a list of strings
- Rolling Hash - Count distinct substrings in a string
Maths
Algorithm Templates
Python Stuff
Miscellaneous
General Thoughts
Something to remember is many STL functions can be applied
for several containers. Remember this.
Eg: count() can be used for vector and strings like Counter() in python.
Like that find_end, find_first_of can be applied.
Some key things to remember when starting off:
-
begin() and end() are used for iterators
-
front() and back() are used for - looking up
-
unordered_map is faster
-
map sorts by key by default
-
iterator to index -> it - v.begin() instead of std::distance()
https://stackoverflow.com/questions/2152986/what-is-the-most-effective-way-to-get-the-index-of-an-iterator-of-an-stdvector -
Rememeber these 2 styles Parsing through a vector and comparing each element
Case1 : Here you go with the iterator approach - and this is how you compare.
for (auto it = words.begin(); it != words.end(); ++it){
if ((*it).compare(word1) == 0)
pos = it - words.begin()
Case 2: You go with the routine approach:
for(int i = 0; i < words.size(); i++) {
if (words[i] == word1)
-
There are 25 prime numbers from 1 to 100.
-
Something to remember here is that:
all these functions - take iterators as I/P's.
But iterators are more like pointers and they can be incremented or decremented -
So this concept called ptr is being used here, so that it can be re-used everywhere else. Guess that's this has been implemented in C++ example is: count() - for compile time polymorphism Like templates