Repository: kiranpalsingh1806/awesome-leetcode
Branch: master
Commit: 809d75c64213
Files: 55
Total size: 329.4 KB
Directory structure:
gitextract_fbu3irtf/
├── README.md
├── markdown/
│ ├── code-2.md
│ └── code.md
├── random/
│ ├── Random.md
│ └── SOLUTIONS.md
└── solutions/
├── base-conversion.md
├── bellman-ford.md
├── binary-trees.md
├── bit-manipulation.md
├── custom-comparator.md
├── design.md
├── dfs.md
├── dijksta.md
├── dp.md
├── euler-circuit.md
├── fenwick-tree.md
├── heaps/
│ ├── kth-largest-element-in-array.md
│ ├── sort-array-by-increasing-frequency.md
│ ├── sort-characters-by-frequency.md
│ └── top-k-frequent-elements.md
├── intervals.md
├── kruskal.md
├── line-sweep.md
├── linked-list.md
├── lis.md
├── manacher.md
├── matrix.md
├── merge-sort.md
├── prefix-state-map.md
├── queries.md
├── rolling-hash/
│ ├── distinct-echo-substrings.md
│ ├── find-substring-with-given-hash-value.md
│ ├── k-divisible-elements-subarray.md
│ ├── longest-common-subpath.md
│ ├── longest-duplicate-substring.md
│ ├── repeated-dna-sequences.md
│ ├── shortest-palindrome.md
│ └── sum-of-scores-of-built-strings.md
├── segment-tree.md
├── sets.md
├── sieve-eratosthenes.md
├── sliding-window/
│ └── count-subarrays-with-fixed-count.md
├── sliding-window.md
├── stack.md
├── stringstream.md
├── sum-of-first-n-natural-numbers.md
├── topological-sort.md
└── trie/
├── concatenated-words.md
├── implement-trie.md
├── k-divisible-elements-subarrays.md
├── maximum-genetic-difference-query.md
├── maximum-xor-of-two-numbers.md
├── palindrome-pairs.md
├── search-suggestions-system.md
└── sum-of-prefix-scores-of-strings.md
================================================
FILE CONTENTS
================================================
================================================
FILE: README.md
================================================
- [1. Backtracking](#1-backtracking)
- [2. Base Conversion](#2-base-conversion)
- [3. Bellman Ford](#3-bellman-ford)
- [4. BFS](#4-bfs)
- [5. Binary Search](#5-binary-search)
- [6. Binary Trees](#6-binary-trees)
- [7. Bit Manipulation](#7-bit-manipulation)
- [8. Bitmasks](#8-bitmasks)
- [9. Count Pairs In Array](#9-count-pairs-in-array)
- [10. Custom Comparator](#10-custom-comparator)
- [11. Design and Implementation](#11-design-and-implementation)
- [12. DFS](#12-dfs)
- [13. Dijkstra](#13-dijkstra)
- [14. Dynamic Programming](#14-dynamic-programming)
- [15. Euler Circuit](#15-euler-circuit)
- [16. Fenwick Tree](#16-fenwick-tree)
- [17. Greedy Scheduling](#17-greedy-scheduling)
- [18. Heaps (Priority Queues)](#18-heaps-priority-queues)
- [19. Intervals](#19-intervals)
- [20. Line Sweep](#20-line-sweep)
- [21. Linked List](#21-linked-list)
- [22. LIS](#22-lis)
- [23. Manacher](#23-manacher)
- [24. Matrix](#24-matrix)
- [25. Merge Sort](#25-merge-sort)
- [26. Minimum Spanning Trees](#26-minimum-spanning-trees)
- [27. Prefix State Map](#27-prefix-state-map)
- [28. Queries](#28-queries)
- [29. Rolling Hash](#29-rolling-hash)
- [30. Segment Tree](#30-segment-tree)
- [31. Sets](#31-sets)
- [32. Sieve of Eratosthenes](#32-sieve-of-eratosthenes)
- [33. Sliding Window](#33-sliding-window)
- [34. Stack](#34-stack)
- [35. Stringstream](#35-stringstream)
- [36. Sum of First N Natural Numbers](#36-sum-of-first-n-natural-numbers)
- [37. Topological Sort](#37-topological-sort)
- [38. Trie](#38-trie)
- [39. Two Dimensional Plane](#39-two-dimensional-plane)
- [40. Two Pointer](#40-two-pointer)
- [41. Union Find](#41-union-find)
## 1. Backtracking
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Combination Sum](https://leetcode.com/problems/combination-sum/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 3 | [Permutations](https://leetcode.com/problems/permutations/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 4 | [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 5 | [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 6 | [Sudoku Solver](https://leetcode.com/problems/sudoku-solver/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 7 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 8 | [Permutations II](https://leetcode.com/problems/permutations-ii/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 9 | [N Queens](https://leetcode.com/problems/n-queens/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 10 | [Combinations](https://leetcode.com/problems/combinations/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 11 | [Subsets](https://leetcode.com/problems/subsets/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 12 | [Word Search](https://leetcode.com/problems/word-search/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 13 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 14 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 15 | [Combination Sum III ](https://leetcode.com/problems/combination-sum-iii/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 2. Base Conversion
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------------- |
| 1 | [Find Unique Binary String](https://leetcode.com/problems/find-unique-binary-string/description/) | Medium | [Solution](/solutions/base-conversion.md) |
## 3. Bellman Ford
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------- |
| 1 | [Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/) | Medium | [Solution](/solutions/bellman-ford.md) |
| 2 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | Medium | [Solution](/solutions/bellman-ford.md) |
## 4. BFS
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Average of Levels In Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/) | Easy | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 5. Binary Search
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Search In Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Find First and Last Position of Element In Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 3 | [Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 6. Binary Trees
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------- |
| 1 | [Sum of Leaft Leaves](https://leetcode.com/problems/sum-of-left-leaves/) | Easy | [Solution](/solutions/binary-trees.md) |
| 2 | [Construct String From Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/) | Easy | [Solution](/solutions/binary-trees.md) |
| 3 | [Average of Levels In Binary Tree](https://leetcode.com/problems/average-of-levels-in-binary-tree/) | Easy | [Solution](/solutions/binary-trees.md) |
| 4 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) | Easy | [Solution](/solutions/binary-trees.md) |
| 5 | [Convert Sorted Array To Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | Easy | [Solution](/solutions/binary-trees.md) |
| 6 | [Sum Root To Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) | Medium | [Solution](/solutions/binary-trees.md) |
| 7 | [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) | Medium | [Solution](/solutions/binary-trees.md) |
| 8 | [Lowest Common Ancestor Of A Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) | Medium | [Solution](/solutions/binary-trees.md) |
| 9 | [Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/) | Medium | [Solution](/solutions/binary-trees.md) |
| 10 | [Construct Binary Tree From Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) | Medium | [Solution](/solutions/binary-trees.md) |
| 11 | [Construct Binary Tree From Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | Medium | [Solution](/solutions/binary-trees.md) |
| 12 | [Binary Tree Pruning](https://leetcode.com/problems/binary-tree-pruning/) | Medium | [Solution](/solutions/binary-trees.md) |
| 13 | [All Nodes Distance K In Binary Tree](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/) | Medium | [Solution](/solutions/binary-trees.md) |
| 14 | [Distribute Coins In Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree/) | Medium | [Solution](/solutions/binary-trees.md) |
| 15 | [Vertical Order Traversal of A Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/) | Hard | [Solution](/solutions/binary-trees.md) |
## 7. Bit Manipulation
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------ |
| 1 | [Power of Two](https://leetcode.com/problems/power-of-two/) | Easy | [Solution](/solutions/bit-manipulation.md) |
| 2 | [Divide Array Into Equal Pairs](https://leetcode.com/problems/divide-array-into-equal-pairs/) | Easy | [Solution](/solutions/bit-manipulation.md) |
| 3 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 4 | [Subsets](https://leetcode.com/problems/subsets/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 5 | [Subsets II](https://leetcode.com/problems/subsets-ii/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 6 | [Check If A String Contains All Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 7 | [Concatenation of Consecutive Binary Numbers](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 8 | [Count Number of Maximum Bitwise OR Subsets](https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 9 | [Largest Combination With Bitwise AND Greater Than Zero](https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 10 | [Maximum XOR After Operations](https://leetcode.com/problems/maximum-xor-after-operations/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 11 | [Smallest Subarrays With Maximum Bitwise OR](https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 12 | [Longest Subarray With Maximum Bitwise AND](https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 13 | [Minimize XOR](https://leetcode.com/problems/minimize-xor/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 14 | [Bitwise XOR of All Pairings](https://leetcode.com/problems/bitwise-xor-of-all-pairings/) | Medium | [Solution](/solutions/bit-manipulation.md) |
| 15 | [Closest Subsequence Sum](https://leetcode.com/problems/closest-subsequence-sum/) | Hard | [Solution](/solutions/bit-manipulation.md) |
| 16 | [Find The Shortest Superstring](https://leetcode.com/problems/find-the-shortest-superstring/) | Hard | [Solution](/solutions/bit-manipulation.md) |
| 17 | [Number of One Bits](https://leetcode.com/problems/number-of-1-bits/) | Easy | [Solution](/solutions/bit-manipulation.md) |
## 8. Bitmasks
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Fair Distribution of Cookies](https://leetcode.com/problems/fair-distribution-of-cookies/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Count Number of Maximum Bitwise OR Subsets](https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 9. Count Pairs In Array
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Count Nice Pairs In An Array](https://leetcode.com/problems/count-nice-pairs-in-an-array/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Count Number of Bad Pairs](https://leetcode.com/problems/count-number-of-bad-pairs/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 10. Custom Comparator
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------- | ---------- | ------------------------------------------- |
| 1 | [Sort The People](https://leetcode.com/problems/sort-the-people/) | Medium | [Solution](/solutions/custom-comparator.md) |
| 2 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | Medium | [Solution](/solutions/custom-comparator.md) |
| 3 | [Bitwise XOR of All Pairings](https://leetcode.com/problems/bitwise-xor-of-all-pairings/) | Medium | [Solution](/solutions/custom-comparator.md) |
## 11. Design and Implementation
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------- | ---------- | -------------------------------- |
| 1 | [Implement Queue Using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | Easy | [Solution](/solutions/design.md) |
| 2 | [Implement Stack Using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | Easy | [Solution](/solutions/design.md) |
| 3 | [Stock Price Fluctuation](https://leetcode.com/problems/stock-price-fluctuation/) | Medium | [Solution](/solutions/design.md) |
| 4 | [Design Circular Deque](https://leetcode.com/problems/design-circular-deque/) | Medium | [Solution](/solutions/design.md) |
| 5 | [LRU Cache](https://leetcode.com/problems/lru-cache/) | Medium | [Solution](/solutions/design.md) |
| 6 | [Time Based Key Value Store](https://leetcode.com/problems/time-based-key-value-store/) | Medium | [Solution](/solutions/design.md) |
| 7 | [Operations On Tree](https://leetcode.com/problems/operations-on-tree/) | Medium | [Solution](/solutions/design.md) |
| 8 | [Design Circular Queue](https://leetcode.com/problems/design-circular-queue/) | Medium | [Solution](/solutions/design.md) |
| 9 | [Design Movie Rental System](https://leetcode.com/problems/design-movie-rental-system/) | Hard | [Solution](/solutions/design.md) |
| 10 | [Design A Text Editor](https://leetcode.com/problems/design-a-text-editor/) | Hard | [Solution](/solutions/design.md) |
## 12. DFS
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------- |
| 1 | [Flood Fill](https://leetcode.com/problems/flood-fill/) | Easy | [Solution](/solutions/dfs.md) |
| 2 | [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) | Medium | [Solution](/solutions/dfs.md) |
| 3 | [Keys and Rooms](https://leetcode.com/problems/keys-and-rooms/) | Medium | [Solution](/solutions/dfs.md) |
| 4 | [Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/) | Medium | [Solution](/solutions/dfs.md) |
| 5 | [Number of Provinces](https://leetcode.com/problems/number-of-provinces/) | Medium | [Solution](/solutions/dfs.md) |
| 6 | [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) | Medium | [Solution](/solutions/dfs.md) |
| 7 | [Interleaving String](https://leetcode.com/problems/interleaving-string/) | Medium | [Solution](/solutions/dfs.md) |
| 8 | [Shortest Bridge](https://leetcode.com/problems/shortest-bridge/) | Medium | [Solution](/solutions/dfs.md) |
| 9 | [Throne Inheritance](https://leetcode.com/problems/throne-inheritance/) | Medium | [Solution](/solutions/dfs.md) |
| 10 | [Detonate The Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/) | Medium | [Solution](/solutions/dfs.md) |
| 11 | [Longest Path With Different Adjacent Characters](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/) | Hard | [Solution](/solutions/dfs.md) |
| 12 | [Create Components With Same Value](https://leetcode.com/problems/create-components-with-same-value/) | Hard | [Solution](/solutions/dfs.md) |
| 13 | [Restore the Array From Adjacent Pairs](https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/description/) | Medium | [Solution](/solutions/dfs.md) |
## 13. Dijkstra
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------- |
| 1 | [Network Delay Time](https://leetcode.com/problems/network-delay-time/) | Medium | [Solution](/solutions/dijksta.md) |
| 2 | [Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/) | Medium | [Solution](/solutions/dijksta.md) |
| 3 | [Path With Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability/) | Medium | [Solution](/solutions/dijksta.md) |
| 4 | [Find The City With The Smallest Number of Neighbors At A Threshold Distance](https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/) | Medium | [Solution](/solutions/dijksta.md) |
| 5 | [Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/) | Medium | [Solution](/solutions/dijksta.md) |
| 6 | [Number of Restricted Paths From First To Last Node](https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/) | Medium | [Solution](/solutions/dijksta.md) |
| 7 | [Number of Ways To Arrive At Destination](https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/) | Medium | [Solution](/solutions/dijksta.md) |
| 8 | [Minimum Cost To Reach Destination In Time](https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/) | Medium | [Solution](/solutions/dijksta.md) |
| 9 | [Minimum Cost To Make At Least One Valid Path In A Grid](https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/) | Hard | [Solution](/solutions/dijksta.md) |
| 10 | [Reachable Nodes in Subdivided Graph](https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/) | Hard | [Solution](/solutions/dijksta.md) |
| 11 | [Design Graph With Shortest Path Calculator](https://leetcode.com/problems/design-graph-with-shortest-path-calculator/) | Hard | [Solution](/solutions/dijksta.md) |
## 14. Dynamic Programming
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------- | ---------- | ---------------------------- |
| 1 | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | Easy | [Solution](/solutions/dp.md) |
| 2 | [Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/) | Easy | [Solution](/solutions/dp.md) |
| 3 | [Best Time To Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) | Easy | [Solution](/solutions/dp.md) |
| 4 | [Jump Game](https://leetcode.com/problems/jump-game/) | Medium | [Solution](/solutions/dp.md) |
| 5 | [Unique Paths](https://leetcode.com/problems/unique-paths/) | Medium | [Solution](/solutions/dp.md) |
| 6 | [Decode Ways](https://leetcode.com/problems/decode-ways/) | Medium | [Solution](/solutions/dp.md) |
| 7 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | Medium | [Solution](/solutions/dp.md) |
| 8 | [House Robber](https://leetcode.com/problems/house-robber/) | Medium | [Solution](/solutions/dp.md) |
| 9 | [Word Break](https://leetcode.com/problems/word-break/) | Medium | [Solution](/solutions/dp.md) |
| 10 | [Coin Change](https://leetcode.com/problems/coin-change/) | Medium | [Solution](/solutions/dp.md) |
| 11 | [Count Number of Texts](https://leetcode.com/problems/count-number-of-texts/description/) | Medium | [Solution](/solutions/dp.md) |
## 15. Euler Circuit
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------- | ---------- | --------------------------------------- |
| 1 | [Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) | Hard | [Solution](/solutions/euler-circuit.md) |
| 2 | [Cracking The Safe](https://leetcode.com/problems/cracking-the-safe/) | Hard | [Solution](/solutions/euler-circuit.md) |
| 3 | [Valid Arrangement of Pairs](https://leetcode.com/problems/valid-arrangement-of-pairs/) | Hard | [Solution](/solutions/euler-circuit.md) |
## 16. Fenwick Tree
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------- |
| 1 | [Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/) | Medium | [Solution](/solutions/fenwick-tree.md) |
| 2 | [Queries On A Permutation With Key](https://leetcode.com/problems/queries-on-a-permutation-with-key/) | Medium | [Solution](/solutions/fenwick-tree.md) |
| 3 | [Create Sorted Array Through Instructions](https://leetcode.com/problems/create-sorted-array-through-instructions/) | Hard | [Solution](/solutions/fenwick-tree.md) |
| 4 | [Count Good Triplets In An Array](https://leetcode.com/problems/count-good-triplets-in-an-array/) | Hard | [Solution](/solutions/fenwick-tree.md) |
## 17. Greedy Scheduling
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Single Threaded CPU](https://leetcode.com/problems/single-threaded-cpu/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 18. Heaps (Priority Queues)
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------ |
| 1 | [Sort Array By Increasing Frequency](https://leetcode.com/problems/sort-array-by-increasing-frequency/) | Easy | [Solution](/solutions/heaps/sort-array-by-increasing-frequency.md) |
| 2 | [Kth Largest Element in An Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | Medium | [Solution](/solutions/heaps/kth-largest-element-in-array.md) |
| 3 | [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | Medium | [Solution](/solutions/heaps/top-k-frequent-elements.md) |
| 4 | [Sort Characters By Frequency](https://leetcode.com/problems/sort-characters-by-frequency/) | Medium | [Solution](/solutions/heaps/sort-characters-by-frequency.md) |
| 5 | [Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) | Medium | [Solution](/solutions/heaps) |
| 6 | [Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/) | Medium | [Solution](/solutions/heaps) |
| 7 | [K Closest Points To Origin](https://leetcode.com/problems/k-closest-points-to-origin/) | Medium | [Solution](/solutions/heaps) |
| 8 | [Reduce Array Size To The Half](https://leetcode.com/problems/reduce-array-size-to-the-half/) | Medium | [Solution](/solutions/heaps) |
| 9 | [Reorganize String](https://leetcode.com/problems/reorganize-string/) | Medium | [Solution](/solutions/heaps) |
| 10 | [Sender With Largest Word Count](https://leetcode.com/problems/sender-with-largest-word-count/) | Medium | [Solution](/solutions/heaps) |
| 11 | [Minimum Difference In Sums After Removal of Elements](https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/) | Hard | [Solution](/solutions/heaps) |
| 12 | [Course Schedule III](https://leetcode.com/problems/course-schedule-iii/) | Hard | [Solution](/solutions/heaps) |
| 13 | [Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack/) | Hard | [Solution](/solutions/heaps) |
## 19. Intervals
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------------- |
| 1 | [Merge Intervals](https://leetcode.com/problems/merge-intervals/) | Medium | [Solution](/solutions/intervals.md) |
| 2 | [Insert Interval](https://leetcode.com/problems/insert-interval/) | Medium | [Solution](/solutions/intervals.md) |
| 3 | [Non Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) | Medium | [Solution](/solutions/intervals.md) |
| 4 | [Minimum Number of Arrows To Burst Balloons](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/) | Medium | [Solution](/solutions/intervals.md) |
| 5 | [My Calendar I](https://leetcode.com/problems/my-calendar-i/) | Medium | [Solution](/solutions/intervals.md) |
| 6 | [Video Stitching](https://leetcode.com/problems/video-stitching/) | Medium | [Solution](/solutions/intervals.md) |
## 20. Line Sweep
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------ |
| 1 | [Maximum Population Year](https://leetcode.com/problems/maximum-population-year/) | Easy | [Solution](/solutions/line-sweep.md) |
| 2 | [Divide Intervals Into Minimum Number of Groups](https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/) | Medium | [Solution](/solutions/line-sweep.md) |
| 3 | [Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/) | Medium | [Solution](/solutions/line-sweep.md) |
| 4 | [Describe The Painting](https://leetcode.com/problems/describe-the-painting/) | Medium | [Solution](/solutions/line-sweep.md) |
| 5 | [Minimum Absolute Difference Queries](https://leetcode.com/problems/minimum-absolute-difference-queries/) | Medium | [Solution](/solutions/line-sweep.md) |
| 6 | [Car Pooling](https://leetcode.com/problems/car-pooling/) | Medium | [Solution](/solutions/line-sweep.md) |
| 7 | [Corporate Flight Bookings](https://leetcode.com/problems/corporate-flight-bookings/) | Medium | [Solution](/solutions/line-sweep.md) |
| 8 | [My Calendar II](https://leetcode.com/problems/my-calendar-ii/) | Medium | [Solution](/solutions/line-sweep.md) |
| 9 | [Minimum Interval To Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) | Hard | [Solution](/solutions/line-sweep.md) |
| 10 | [My Calendar III](https://leetcode.com/problems/my-calendar-iii/) | Hard | [Solution](/solutions/line-sweep.md) |
| 11 | [The Skyline Problem](https://leetcode.com/problems/the-skyline-problem/) | Hard | [Solution](/solutions/line-sweep.md) |
| 12 | [Number of Flowers In Full Bloom](https://leetcode.com/problems/number-of-flowers-in-full-bloom/) | Hard | [Solution](/solutions/line-sweep.md) |
## 21. Linked List
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------- |
| 1 | [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | Easy | [Solution](/solutions/linked-list.md) |
| 2 | [Remove Duplicates From Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | Easy | [Solution](/solutions/linked-list.md) |
| 3 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | Easy | [Solution](/solutions/linked-list.md) |
| 4 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | Easy | [Solution](/solutions/linked-list.md) |
| 5 | [Middle of The Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | Easy | [Solution](/solutions/linked-list.md) |
| 6 | [Intersection of Two Linked List](https://leetcode.com/problems/intersection-of-two-linked-lists/) | Easy | [Solution](/solutions/linked-list.md) |
| 7 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium | [Solution](/solutions/linked-list.md) |
| 8 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 9 | [Rotate List](https://leetcode.com/problems/rotate-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 10 | [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 11 | [Sort List](https://leetcode.com/problems/sort-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 12 | [Reorder List](https://leetcode.com/problems/reorder-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 13 | [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/) | Medium | [Solution](/solutions/linked-list.md) |
| 14 | [Remove Duplicates From Sorted List II](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/) | Medium | [Solution](/solutions/linked-list.md) |
| 15 | [Partition List](https://leetcode.com/problems/partition-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 16 | [Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) | Medium | [Solution](/solutions/linked-list.md) |
| 17 | [Flatten Binary Tree To Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 18 | [Populating Next Right Pointers In Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) | Medium | [Solution](/solutions/linked-list.md) |
| 19 | [Copy List With Random Pointers](https://leetcode.com/problems/copy-list-with-random-pointer/) | Medium | [Solution](/solutions/linked-list.md) |
| 20 | [Delete Node In A Linked List](https://leetcode.com/problems/delete-node-in-a-linked-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 21 | [Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 22 | [Swapping Nodes In A Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) | Medium | [Solution](/solutions/linked-list.md) |
| 23 | [Merge Nodes In Between Zeros](https://leetcode.com/problems/merge-nodes-in-between-zeros/) | Medium | [Solution](/solutions/linked-list.md) |
| 24 | [Reverse Nodes In K Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) | Hard | [Solution](/solutions/linked-list.md) |
| 25 | [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | Hard | [Solution](/solutions/linked-list.md) |
## 22. LIS
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ----------------------------- |
| 1 | [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) | Medium | [Solution](/solutions/lis.md) |
| 2 | [Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/) | Medium | [Solution](/solutions/lis.md) |
| 3 | [Minimum Number of Removals To Make Mountain Array](https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/) | Hard | [Solution](/solutions/lis.md) |
| 4 | [Find The Longest Valid Obstacle Course At Each Position](https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/) | Hard | [Solution](/solutions/lis.md) |
## 23. Manacher
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ---------------------------------- |
| 1 | [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) | Medium | [Solution](/solutions/manacher.md) |
| 2 | [Maximum Product of The Length of Two Palindromic Substrings](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/) | Hard | [Solution](/solutions/manacher.md) |
## 24. Matrix
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------- |
| 1 | [Transpost Matrix](https://leetcode.com/problems/transpose-matrix/) | Easy | [Solution](/solutions/matrix.md) |
| 2 | [Count Submatrices With All Ones](https://leetcode.com/problems/count-submatrices-with-all-ones/) | Medium | [Solution](/solutions/matrix.md) |
| 3 | [Maximal Square](https://leetcode.com/problems/maximal-square/) | Medium | [Solution](/solutions/matrix.md) |
| 4 | [Shortest Path In Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) | Medium | [Solution](/solutions/matrix.md) |
| 5 | [Sort The Matrix Diagonally](https://leetcode.com/problems/sort-the-matrix-diagonally/) | Medium | [Solution](/solutions/matrix.md) |
| 6 | [Count Square Submatrices With All Ones](https://leetcode.com/problems/count-square-submatrices-with-all-ones/) | Medium | [Solution](/solutions/matrix.md) |
| 7 | [Number of Submatrices That Sum To Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/) | Hard | [Solution](/solutions/matrix.md) |
| 8 | [Maximal Rectangle](https://leetcode.com/problems/maximal-rectangle/) | Hard | [Solution](/solutions/matrix.md) |
## 25. Merge Sort
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------ |
| 1 | [Sort List](https://leetcode.com/problems/sort-list/) | Medium | [Solution](/solutions/merge-sort.md) |
| 2 | [Count of Smaller Numbers After Self](https://leetcode.com/problems/count-of-smaller-numbers-after-self/) | Medium | [Solution](/solutions/merge-sort.md) |
| 3 | [Count of Range Sum](https://leetcode.com/problems/count-of-range-sum/) | Medium | [Solution](/solutions/merge-sort.md) |
| 4 | [Reverse Pairs](https://leetcode.com/problems/reverse-pairs/) | Medium | [Solution](/solutions/merge-sort.md) |
| 5 | [Number of Pairs Satisfying Inequality](https://leetcode.com/problems/number-of-pairs-satisfying-inequality/) | Medium | [Solution](/solutions/merge-sort.md) |
## 26. Minimum Spanning Trees
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------- |
| 1 | [Min Cost To Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/) | Medium | [Solution](/solutions/kruskal.md) |
| 2 | [Find Critical And Pseudo Critical Edges in Minimum Spanning Tree](https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/) | Medium | [Solution](/solutions/kruskal.md) |
## 27. Prefix State Map
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------ |
| 1 | [Contiguous Array](https://leetcode.com/problems/contiguous-array/) | Medium | [Solution](/solutions/prefix-state-map.md) |
| 2 | [Find The Longest Substring Containing Vowels In Even Counts](https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/) | Medium | [Solution](/solutions/prefix-state-map.md) |
| 3 | [Find Longest Awesome Substring](https://leetcode.com/problems/find-longest-awesome-substring/) | Medium | [Solution](/solutions/prefix-state-map.md) |
| 4 | [Number of Wonderful Substrings](https://leetcode.com/problems/number-of-wonderful-substrings/submissions/) | Medium | [Solution](/solutions/prefix-state-map.md) |
## 28. Queries
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------- | ---------- | --------------------------------- |
| 1 | [Most Beautiful Item For Each Query](https://leetcode.com/problems/most-beautiful-item-for-each-query/) | Medium | [Solution](/solutions/queries.md) |
| 2 | [Queries On Number of Points Inside A Circle](https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/) | Medium | [Solution](/solutions/queries.md) |
| 3 | [Range Frequency Queries](https://leetcode.com/problems/range-frequency-queries/) | Medium | [Solution](/solutions/queries.md) |
| 4 | [XOR Queries of a Subarray](https://leetcode.com/problems/xor-queries-of-a-subarray/) | Medium | [Solution](/solutions/queries.md) |
| 5 | [Queries On A Permutation With Key](https://leetcode.com/problems/queries-on-a-permutation-with-key/) | Medium | [Solution](/solutions/queries.md) |
| 6 | [Subrectangle Queries](https://leetcode.com/problems/subrectangle-queries/) | Medium | [Solution](/solutions/queries.md) |
| 7 | [Minimum Absolute Difference Queries](https://leetcode.com/problems/minimum-absolute-difference-queries/) | Medium | [Solution](/solutions/queries.md) |
| 8 | [Maximum Genetic Difference Query](https://leetcode.com/problems/maximum-genetic-difference-query/) | Hard | [Solution](/solutions/queries.md) |
## 29. Rolling Hash
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) | Medium | [Solution](/solutions/rolling-hash/repeated-dna-sequences.md) |
| 2 | [Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/) | Medium | [Solution](/solutions/rolling-hash/shortest-palindrome.md) |
| 3 | [Longest Duplicate Substring](https://leetcode.com/problems/longest-duplicate-substring/) | Medium | [Solution](/solutions/rolling-hash/longest-duplicate-substring.md) |
| 4 | [Distinct Echo Substrings](https://leetcode.com/problems/distinct-echo-substrings/) | Medium | [Solution](/solutions/rolling-hash/distinct-echo-substrings.md) |
| 5 | [K Divisible Elements Subarrays](https://leetcode.com/problems/k-divisible-elements-subarrays/) | Medium | [Solution](/solutions/rolling-hash/k-divisible-elements-subarray.md) |
| 6 | [Sum of Scores of Built Strings](https://leetcode.com/problems/sum-of-scores-of-built-strings/) | Hard | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 7 | [Find Substring With Given Hash Value](https://leetcode.com/problems/find-substring-with-given-hash-value/) | Hard | [Solution](/solutions/rolling-hash/find-substring-with-given-hash-value.md) |
| 8 | [Longest Common Subpath](https://leetcode.com/problems/longest-common-subpath/) | Hard | [Solution](/solutions/rolling-hash/longest-common-subpath.md) |
## 30. Segment Tree
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------ | ---------- | -------------------------------------- |
| 1 | [Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) | Medium | [Solution](/solutions/segment-tree.md) |
| 2 | [Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/) | Medium | [Solution](/solutions/segment-tree.md) |
| 3 | [Longest Increasing Subseqence - II](https://leetcode.com/problems/longest-increasing-subsequence-ii/) | Medium | [Solution](/solutions/segment-tree.md) |
| 4 | [Shifting Letters - II](https://leetcode.com/problems/shifting-letters-ii/) | Medium | [Solution](/solutions/segment-tree.md) |
| 5 | [Falling Squares](https://leetcode.com/problems/falling-squares/) | Hard | [Solution](/solutions/segment-tree.md) |
## 31. Sets
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------ |
| 1 | [Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) | Medium | [Solution](/solutions/sets.md) |
## 32. Sieve of Eratosthenes
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------- | ---------- | -------------------------------------------- |
| 1 | [Count Primes](https://leetcode.com/problems/count-primes/) | Medium | [Solution](/solutions/sieve-eratosthenes.md) |
| 2 | [Four Divisors](https://leetcode.com/problems/four-divisors/) | Medium | [Solution](/solutions/sieve-eratosthenes.md) |
## 33. Sliding Window
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------- |
| 1 | [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | Medium | [Solution](/solutions/sliding-window.md) |
| 2 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) | Medium | [Solution](/solutions/sliding-window.md) |
| 3 | [Number of Smooth Descent Periods of Stock](https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/) | Medium | [Solution](/solutions/sliding-window.md) |
| 4 | [Maximize The Confusion of An Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) | Medium | [Solution](/solutions/sliding-window.md) |
| 5 | [Frequency of Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) | Medium | [Solution](/solutions/sliding-window.md) |
| 6 | [Max Consecutive Ones - III](https://leetcode.com/problems/max-consecutive-ones-iii/) | Medium | [Solution](/solutions/sliding-window.md) |
| 7 | [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) | Medium | [Solution](/solutions/sliding-window.md) |
| 8 | [Permutation In String](https://leetcode.com/problems/permutation-in-string/) | Medium | [Solution](/solutions/sliding-window.md) |
| 9 | [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | Hard | [Solution](/solutions/sliding-window.md) |
| 10 | [Substring With Concatenation Of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | Hard | [Solution](/solutions/sliding-window.md) |
| 11 | [Count Subarrays With Fixed Count](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/) | Hard | [Solution](/solutions/sliding-window/count-subarrays-with-fixed-count.md) |
## 34. Stack
| S.No | Problem | Difficulty | Solution |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------- |
| 1 | [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | Easy | [Solution](/solutions/stack.md) |
| 2 | [Implement Queue Using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/) | Easy | [Solution](/solutions/stack.md) |
| 3 | [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/) | Easy | [Solution](/solutions/stack.md) |
| 4 | [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) | Easy | [Solution](/solutions/stack.md) |
| 5 | [Min Stack](https://leetcode.com/problems/min-stack/) | Medium | [Solution](/solutions/stack.md) |
| 6 | [Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/) | Medium | [Solution](/solutions/stack.md) |
| 7 | [132 Patterns](https://leetcode.com/problems/132-pattern/) | Medium | [Solution](/solutions/stack.md) |
| 8 | [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | Medium | [Solution](/solutions/stack.md) |
| 9 | [Score of Parentheses](https://leetcode.com/problems/score-of-parentheses/) | Medium | [Solution](/solutions/stack.md) |
| 10 | [Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) | Medium | [Solution](/solutions/stack.md) |
| 11 | [Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/) | Medium | [Solution](/solutions/stack.md) |
| 12 | [The Number of Weak Characters In The Game](https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/) | Medium | [Solution](/solutions/stack.md) |
| 13 | [Construct Smallest Number From DI String](https://leetcode.com/problems/construct-smallest-number-from-di-string/) | Medium | [Solution](/solutions/stack.md) |
| 14 | [Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack/) | Medium | [Solution](/solutions/stack.md) |
| 15 | [Basic Calculator](https://leetcode.com/problems/basic-calculator/) | Medium | [Solution](/solutions/stack.md) |
| 16 | [Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/) | Medium | [Solution](/solutions/stack.md) |
| 17 | [Using A Robot To Print The Lexicographically Smallest String](https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/) | Medium | [Solution](/solutions/stack.md) |
## 35. Stringstream
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------- | ---------- | -------------------------------------- |
| 1 | [Reverse Words In A String-III](https://leetcode.com/problems/reverse-words-in-a-string-iii/) | Medium | [Solution](/solutions/stringstream.md) |
| 2 | [Find Duplicate File In System](https://leetcode.com/problems/find-duplicate-file-in-system/) | Medium | [Solution](/solutions/stringstream.md) |
| 3 | [Apply Discount To Prices](https://leetcode.com/problems/apply-discount-to-prices/) | Medium | [Solution](/solutions/stringstream.md) |
## 36. Sum of First N Natural Numbers
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------- | ---------- | -------------------------------------------------------- |
| 1 | [Count Number of Homogenous Substrings](https://leetcode.com/problems/count-number-of-homogenous-substrings/description/) | Medium | [Solution](/solutions/sum-of-first-n-natural-numbers.md) |
| 2 | [Number of Substrings With Only 1s](https://leetcode.com/problems/number-of-substrings-with-only-1s/description/) | Medium | [Solution](/solutions/sum-of-first-n-natural-numbers.md) |
## 37. Topological Sort
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------ |
| 1 | [Course Schedule](https://leetcode.com/problems/course-schedule/) | Medium | [Solution](/solutions/topological-sort.md) |
| 2 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) | Medium | [Solution](/solutions/topological-sort.md) |
| 3 | [Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/) | Medium | [Solution](/solutions/topological-sort.md) |
| 4 | [Longest Incresing Path In A Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) | Medium | [Solution](/solutions/topological-sort.md) |
| 5 | [All Ancestors of a Node In Directed Acyclic Graph](https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/) | Medium | [Solution](/solutions/topological-sort.md) |
| 6 | [Number of Ways To Arrive At Destination](https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/) | Medium | [Solution](/solutions/topological-sort.md) |
| 7 | [Parallel Courses III](https://leetcode.com/problems/parallel-courses-iii/) | Hard | [Solution](/solutions/topological-sort.md) |
| 8 | [Build A Matrix With Conditions](https://leetcode.com/problems/build-a-matrix-with-conditions/) | Hard | [Solution](/solutions/topological-sort.md) |
## 38. Trie
| S.No | Problem | Difficulty | Solution |
| ---- | --------------------------------------------------------------------------------------------------------------- | ---------- | ---------------------------------------------------------------- |
| 1 | [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/) | Medium | [Solution](/solutions/trie/implement-trie.md) |
| 2 | [Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/) | Medium | [Solution](/solutions/trie/search-suggestions-system.md) |
| 3 | [Maximum XOR of Two Numbers In An Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/) | Medium | [Solution](/solutions/trie/maximum-xor-of-two-numbers.md) |
| 4 | [K Divisible Elements Subarray](https://leetcode.com/problems/k-divisible-elements-subarrays/) | Medium | [Solution](/solutions/trie/k-divisible-elements-subarrays.md) |
| 5 | [Maximum Genetic Difference Query](https://leetcode.com/problems/maximum-genetic-difference-query/) | Hard | [Solution](/solutions/trie//maximum-genetic-difference-query.md) |
| 6 | [Concatenated Words](https://leetcode.com/problems/concatenated-words/) | Hard | [Solution](/solutions/trie/concatenated-words.md) |
| 7 | [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/) | Hard | [Solution](/solutions/trie/palindrome-pairs.md) |
| 8 | [Sum of Prefix Scores of Strings](https://leetcode.com/problems/sum-of-prefix-scores-of-strings/) | Hard | [Solution](/solutions/trie/sum-of-prefix-scores-of-strings.md) |
## 39. Two Dimensional Plane
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Max Points On A Line](https://leetcode.com/problems/max-points-on-a-line/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Min Cost To Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 3 | [Queries On Number of Points Inside A Circle](https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 4 | [Detonate The Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 40. Two Pointer
| S.No | Problem | Difficulty | Solution |
| ---- | ------------------------------------------------------------------------------------------------------------ | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Remove Duplicates From Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) | Easy | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 3 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) | Easy | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 4 | [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 5 | [Container With Most Water](https://leetcode.com/problems/container-with-most-water/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 6 | [3Sum](https://leetcode.com/problems/3sum/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 7 | [3Sum Closest](https://leetcode.com/problems/3sum-closest/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 8 | [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 9 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 10 | [Sort Colors](https://leetcode.com/problems/sort-colors/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 11 | [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 12 | [Linked List Cycle-II](https://leetcode.com/problems/linked-list-cycle-ii/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 13 | [Reorder List](https://leetcode.com/problems/reorder-list/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 14 | [Sort List](https://leetcode.com/problems/sort-list/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 15 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 16 | [Lexicographically Smallest Palindrome](https://leetcode.com/problems/lexicographically-smallest-palindrome) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
## 41. Union Find
| S.No | Problem | Difficulty | Solution |
| ---- | ---------------------------------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------------------------- |
| 1 | [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 2 | [Number of Islands](https://leetcode.com/problems/number-of-islands/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 3 | [Number of Provinces](https://leetcode.com/problems/number-of-provinces/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 4 | [Redundant Connections](https://leetcode.com/problems/redundant-connection/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 5 | [Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 6 | [Is Graph Bipartite ?](https://leetcode.com/problems/is-graph-bipartite/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 7 | [Satifiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 8 | [Smallest String With Swaps](https://leetcode.com/problems/smallest-string-with-swaps/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
| 9 | [Number of Good Paths](https://leetcode.com/problems/number-of-good-paths/) | Medium | [Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md) |
================================================
FILE: markdown/code-2.md
================================================
## Heading here
```cpp
```
================================================
FILE: markdown/code.md
================================================
## Heading here
View Code
```cpp
```
================================================
FILE: random/Random.md
================================================
# LeetCode Problems
|Index|Problem|Topic|Solution|
|------|------|--------|------|
|1|[Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|2|[Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|3|[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|Custom Comparator|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|4|[Min Cost To Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/)|Kruskal Algorithm|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|5|[Power(X, n)](https://leetcode.com/problems/powx-n/)|Recursion|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|6|[Critical Connections in a Network](https://leetcode.com/problems/critical-connections-in-a-network/)|Tarjan's Algorithm|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|7|[Longest Increasing Path in Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)|DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|8|[Valid Arrangement of Pairs](https://leetcode.com/problems/valid-arrangement-of-pairs/)|Euler Tour|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|9|[Next Greater Element II](https://leetcode.com/problems/next-greater-element-ii/)|Stack|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|10|[Container With Most Water](https://leetcode.com/problems/container-with-most-water/)|Two Pointer|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|11|[Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)|Trie|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|12|[Sort the Matrix Diagonally](https://leetcode.com/problems/sort-the-matrix-diagonally/)|Matrix|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|13|[Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)|Sliding Window|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|14|[Increasing Triplet Subsequence](https://leetcode.com/problems/increasing-triplet-subsequence/)|LIS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|15|[Target Sum](https://leetcode.com/problems/target-sum/)|Recursion, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|16|[Check if there is Valid Partition For The Array](https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/)|Recursion, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|17|[Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)|Union Find|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|18|[Valid Sudoku](https://leetcode.com/problems/valid-sudoku/)|BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|19|[My Calendar I](https://leetcode.com/problems/my-calendar-i/)|Binary Search|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|20|[Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/)|Deque, Sliding Window|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|21|[Best Time To Buy and Sell Stock]()|Array, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|22|[Maximum Subarray]()|Kadane Algorithm|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|23|[Cracking The Safe]()|Euler Tour, Heirholzer Algorithm|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|24|[Find If Path Exists In Graph]()|Graphs, BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|25|[Next Greater Node In Linked List]()|Linked List, Stack|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|26|[Repeated Substring Pattern]()|String|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|27|[Search Suggestion System]()|Trie|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|28|[Merge K Sorted Lists]()|Heaps, Custom Comparator|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|29|[Daily Temperatures]()|Monotonous Stack|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|30|[Merge Intervals]()|Intervals|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|31|[Word Ladder]()|BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|32|[3 Sum]()|Two Pointer|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|33|[Flatten Binary Tree To Linked List]()|Linked List, Stacks|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|34|[Sum of Subarray Minimums]()|Monotonous Stack|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|35|[Median of Two Sorted Arrays]()|Binary Search|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|36|[LRU Cache]()|Data Structure, Design|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|37|[Gas Station]()|Greedy, Prefix Sum|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|38|[Max Points On A Line]()|Slope Of Line|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|39|[Largest Rectangle In Histogram]()|Monotonic Stack|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|40|[Regular Expression Matching]()|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|41|[Minimum Deletions To Make Character Frequencies Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/)|Strings|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|42|[Jump Game II](https://leetcode.com/problems/jump-game-ii/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|43|[Count Good Nodes In Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/)|Binary Trees|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|44|[Unique Paths](https://leetcode.com/problems/unique-paths/)|DP, Grid|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|45|[Coin Change](https://leetcode.com/problems/coin-change/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|46|[Is Graph Bipartite ?](https://leetcode.com/problems/is-graph-bipartite/)|DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|47|[Frequency of Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/)|Sliding Window|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|48|[Group Anagrams](https://leetcode.com/problems/group-anagrams/)|Sorting|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|49|[Satisfiability Of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/)|Union Find|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|50|[Range Sum BST](https://leetcode.com/problems/range-sum-of-bst/)|Binary Search Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|51|[Number of Islands](https://leetcode.com/problems/number-of-islands/)|DFS, BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|52|[Wildcard Matching](https://leetcode.com/problems/wildcard-matching/)|Strings, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|53|[Min Stack](https://leetcode.com/problems/min-stack/)|Data Structure|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|54|[Permutations](https://leetcode.com/problems/permutations/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|55|[Combinations](https://leetcode.com/problems/combinations/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|56|[Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)|BST|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|57|[Peak Index In A Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/)|Binary Search|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|58|[Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|59|[Find Minimum In Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)|Binary Search|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|60|[Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)|BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|61|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)|Sliding Window|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|62|[Combination Sum](https://leetcode.com/problems/combination-sum/)|Backtracking, DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|63|[N-Queens](https://leetcode.com/problems/n-queens/)|Grid, Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|64|[Subsets](https://leetcode.com/problems/subsets/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|65|[Pascal's Triangle](https://leetcode.com/problems/pascals-triangle/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|66|[House Robber II](https://leetcode.com/problems/house-robber-ii/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|67|[Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/)|DP, Subset Sum|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|68|[Number of Submatrices That Sum To Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/)|Grid, Prefix Sum 2D|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|69|[Shortest Path In Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/)|BFS, Shortest Path|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|70|[Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)|BST, Recursion|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|71|[Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group/)|Linked List|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|72|[Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|73|[Find Missing Positive](https://leetcode.com/problems/first-missing-positive/)|Implementation|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|74|[Edit Distance](https://leetcode.com/problems/edit-distance/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|75|[Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|76|[Shifting Letters II](https://leetcode.com/problems/shifting-letters-ii/)|Line Sweep, Fenwick Tree, Segment Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|77|[Build a Matrix With Conditions](https://leetcode.com/problems/build-a-matrix-with-conditions/)|Topological Sort|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|78|[Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-bst/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|79|[Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)|DFS, Grid|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|80|[Delete And Earn](https://leetcode.com/problems/delete-and-earn/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|81|[Permutations II](https://leetcode.com/problems/permutations-ii/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|82|[Combination Sum II](https://leetcode.com/problems/combination-sum-ii/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|83|[Non Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)|Intervals|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|84|[Best Time To Buy and Sell Stocks With Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)|Recursion, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|85|[Maximum XOR of Two Numbers In An Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/)|Bitmasks, Trie|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|86|[Implement Queue Using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)|Data Structure|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|87|[Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/)|Sliding Window|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|88|[Number of Visible People In A Queue](https://leetcode.com/problems/number-of-visible-people-in-a-queue/)|Mono-Deque, Binary Search|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|89|[Describe The Painting](https://leetcode.com/problems/describe-the-painting/)|Line Sweep|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|90|[Flood Fill](https://leetcode.com/problems/flood-fill/)|Grid, BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|91|[Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)|Backtracking|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|92|[Path With Maximum Gold](https://leetcode.com/problems/path-with-maximum-gold/)|DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|93|[Counting Bits](https://leetcode.com/problems/counting-bits/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|94|[Word Break](https://leetcode.com/problems/word-break/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|95|[Find Median From Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)|Heaps|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|96|[Single Threaded CPU](https://leetcode.com/problems/single-threaded-cpu/)|Greedy Scheduling|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|97|[Contiguous Array](https://leetcode.com/problems/contiguous-array/)|Prefix State Map|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|98|[Falling Squares](https://leetcode.com/problems/falling-squares/)|Segment Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|99|[Minimum XOR Sum of Two Arrays](https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/)|Bitmasks, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|100|[Maximum Profit In Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/)|Binary Search, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|101|[Find Minimum Time To Finish All Jobs](https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/)|Bitmasks, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|102|[Course Schedule](https://leetcode.com/problems/course-schedule/)|Topological Sort|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|103|[Minimum Height Trees](https://leetcode.com/problems/minimum-height-trees/)|Tree Ring Order Traversal|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|104|[Russian Doll Envelopes](https://leetcode.com/problems/russian-doll-envelopes/)|LIS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|105|[Maximum AND Sum of Array](https://leetcode.com/problems/maximum-and-sum-of-array/)|Bitmasks, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|106|[Maximum Number of Robots Within Budget](https://leetcode.com/problems/maximum-number-of-robots-within-budget/)|Sliding Window, Binary Search, Sparse Table|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|107|[Find Longest Awesome Substring](https://leetcode.com/problems/find-longest-awesome-substring/)|Prefix State Map|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|108|[Maximum Rows Covered By Columns](https://leetcode.com/problems/maximum-rows-covered-by-columns/)|Bitmasks|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|109|[Create Sorted Array Through Instructions](https://leetcode.com/problems/create-sorted-array-through-instructions/)|Binary Indexed Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|110|[Maximum Students Taking Exam](https://leetcode.com/problems/maximum-students-taking-exam/)|Bitmasks|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|111|[Number of Ways To Reach A Position After Exactly K Steps](https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/)|Recursion, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|112|[Find The Longest Substring Containing Vowels In Even Counts](https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/)|Prefix State Map|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|113|[Maximum Earnings From Taxi](https://leetcode.com/problems/maximum-earnings-from-taxi/)|DP, Binary Search|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|114|[Vertical Order Traversal Of A Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|115|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|116|[Count Primes](https://leetcode.com/problems/count-primes/)|Sieve of Eratosthenes|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|117|[Find The Shortest Superstring](https://leetcode.com/problems/find-the-shortest-superstring/)|Bitmasks, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|118|[Sum Root To Leaf Nodes](https://leetcode.com/problems/sum-root-to-leaf-numbers/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|119|[Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|120|[Count Number of Maximum Bitwise Or Subsets](https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/)|Bitmasks|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|121|[Jump Game III](https://leetcode.com/problems/jump-game-iii/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|122|[Operations On Tree](https://leetcode.com/problems/operations-on-tree/)|Trees|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|123|[Minimum Operations To Convert Number](https://leetcode.com/problems/minimum-operations-to-convert-number/)|BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|124|[Egg Drop With 2 Eggs And N Floors](https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/)|DP, Maths|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|125|[Time Needed To Inform All Employees](https://leetcode.com/problems/time-needed-to-inform-all-employees/)|BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|126|[Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/)|Design|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|127|[Shortest Bridge](https://leetcode.com/problems/shortest-bridge/)|DFS, BFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|128|[Flip String To Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/)|String|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|129|[Longest Increasing Subsequence - II](https://leetcode.com/problems/longest-increasing-subsequence-ii/)|Segment Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|130|[Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/)|DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|131|[Detonate The Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/)|DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|132|[Fair Distribution of Cookies](https://leetcode.com/problems/fair-distribution-of-cookies/)|Bitmasks, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|133|[Minimum Cost To Reach Destination In Time](https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/)|Dijkstra|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|134|[Longest Substring Of One Repeating Character](https://leetcode.com/problems/longest-substring-of-one-repeating-character/)|Segment Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|135|[Predict The Winner](https://leetcode.com/problems/predict-the-winner/)|Recursion, DP|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|136|[Path With Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/)|Dijkstra|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|137|[Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/)|Bellman Ford, Dijkstra|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|138|[Minimum Cost To Make at Least One Valid Path In a Grid](https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/)|BFS + DP, Dijkstra|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|139|[Frog Jump](https://leetcode.com/problems/frog-jump/)|DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|140|[Find Eventual Safe State](https://leetcode.com/problems/find-eventual-safe-states/)|Topological Sort|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|141|[Number of Ways To Arrive At Destination](https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/)|Dijkstra|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|142|[Sort List](https://leetcode.com/problems/sort-list/)|Merge Sort, Quick Sort|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|143|[Frog Position After T Seconds](https://leetcode.com/problems/frog-position-after-t-seconds/)|DFS|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|144|[Longest Zigzag Path In A Binary Tree](https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|145|[Balance A Binary Search Tree](https://leetcode.com/problems/balance-a-binary-search-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|146|[Linked List In Binary Tree](https://leetcode.com/problems/linked-list-in-binary-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|147|[Find Substring With Given Hash Value](https://leetcode.com/problems/find-substring-with-given-hash-value/)|Rolling Hash|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|148|[Distinct Echo Substrings](https://leetcode.com/problems/distinct-echo-substrings/)|Rolling Hash|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|149|[Longest Duplicate Substring](https://leetcode.com/problems/longest-duplicate-substring/)|Rolling Hash|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|150|[Distribute Coins In Binary Tree](https://leetcode.com/problems/distribute-coins-in-binary-tree/)|Binary Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|151|[Range Sum Query Mutable](https://leetcode.com/problems/range-sum-query-mutable/)|Segment Tree|[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|152|[Shortest Palindrome](https://leetcode.com/problems/shortest-palindrome/)||[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|153|[Maximum Number of Events That Can Be Attended](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/)||[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|154|[Maximum Product of The Length of Two Palindromic Substrings](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/)||[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|155|[Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/)||[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|156|[K Divisible Elements Subarray](https://leetcode.com/problems/k-divisible-elements-subarrays/)||[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
|157|[]()||[Solution](https://github.com/kiranpalsingh1806/awesome-dsa/blob/master/SOLUTIONS.md)|
================================================
FILE: random/SOLUTIONS.md
================================================
# Table of Contents
- [Table of Contents](#table-of-contents)
- [1. Longest Increasing Subsequence](#1-longest-increasing-subsequence)
- [2. Generate Parentheses](#2-generate-parentheses)
- [3. Sort Array By Parity](#3-sort-array-by-parity)
- [4. Min Cost To Connect All Points](#4-min-cost-to-connect-all-points)
- [5. Power(x, n)](#5-powerx-n)
- [6. Critical Connections In A Network](#6-critical-connections-in-a-network)
- [7. Longest Increasing Path In A Matrix](#7-longest-increasing-path-in-a-matrix)
- [8. Valid Arrangement of Pairs](#8-valid-arrangement-of-pairs)
- [9. Next Greater Element II](#9-next-greater-element-ii)
- [10. Container With Most Water](#10-container-with-most-water)
- [11. Implement Trie (Prefix Tree)](#11-implement-trie-prefix-tree)
- [12. Sort The Matrix Diagonally](#12-sort-the-matrix-diagonally)
- [13. Minimum Window Substring](#13-minimum-window-substring)
- [14. Increasing Triplet Subsequence](#14-increasing-triplet-subsequence)
- [15. Target Sum](#15-target-sum)
- [16. Check If There Is A Valid Partition For The Array](#16-check-if-there-is-a-valid-partition-for-the-array)
- [17. Longest Consecutive Sequence](#17-longest-consecutive-sequence)
- [18. Valid Sudoku](#18-valid-sudoku)
- [19. My Calendar I](#19-my-calendar-i)
- [20. Sliding Window Maximum](#20-sliding-window-maximum)
- [21. Best Time To Buy and Sell Stock](#21-best-time-to-buy-and-sell-stock)
- [22. Maximum Subarray](#22-maximum-subarray)
- [23. Cracking The Safe](#23-cracking-the-safe)
- [24. Find If Path Exists In Graph](#24-find-if-path-exists-in-graph)
- [25. Next Greater Node In Linked List](#25-next-greater-node-in-linked-list)
- [26. Repeated Substring Pattern](#26-repeated-substring-pattern)
- [27. Search Suggestion System](#27-search-suggestion-system)
- [28. Merge K Sorted Lists](#28-merge-k-sorted-lists)
- [29. Daily Temperatures](#29-daily-temperatures)
- [30. Merge Intervals](#30-merge-intervals)
- [31. Word Ladder](#31-word-ladder)
- [32. 3Sum](#32-3sum)
- [33. Flatten Binary Tree To Linked List](#33-flatten-binary-tree-to-linked-list)
- [34. Sum of Subarray Minimums](#34-sum-of-subarray-minimums)
- [35. Median of Two Sorted Arrays](#35-median-of-two-sorted-arrays)
- [36. LRU Cache](#36-lru-cache)
- [37. Gas Station](#37-gas-station)
- [38. Max Points On A Line](#38-max-points-on-a-line)
- [39. Largest Rectangle In Histogram](#39-largest-rectangle-in-histogram)
- [40. Regular Expression Matching](#40-regular-expression-matching)
- [41. Minimum Deletions To Make Character Frequencies Unique](#41-minimum-deletions-to-make-character-frequencies-unique)
- [42. Jump Game II](#42-jump-game-ii)
- [43. Count Good Nodes In Binary Tree](#43-count-good-nodes-in-binary-tree)
- [44. Unique Paths](#44-unique-paths)
- [45. Coin Change](#45-coin-change)
- [46. Is Graph Bipartite ?](#46-is-graph-bipartite-)
- [47. Frequency of Most Frequent Elements](#47-frequency-of-most-frequent-elements)
- [48. Group Anagrams](#48-group-anagrams)
- [49. Satisfiability of Equality Equations](#49-satisfiability-of-equality-equations)
- [50. Range Sum BST](#50-range-sum-bst)
- [51. Number of Islands](#51-number-of-islands)
- [52. Wildcard Matching](#52-wildcard-matching)
- [53. Min Stack](#53-min-stack)
- [54. Permutations](#54-permutations)
- [55. Combinations](#55-combinations)
- [56. Diameter of Binary Tree](#56-diameter-of-binary-tree)
- [57. Peak Index In Mountain Array](#57-peak-index-in-mountain-array)
- [58. Maximum Depth of Binary Tree](#58-maximum-depth-of-binary-tree)
- [59. Find Minimum In Rotated Sorted Array](#59-find-minimum-in-rotated-sorted-array)
- [60. Binary Tree Zigzag Level Order Traversal](#60-binary-tree-zigzag-level-order-traversal)
- [61. Longest Substring Without Repeating Characters](#61-longest-substring-without-repeating-characters)
- [62. Combination Sum](#62-combination-sum)
- [63. N-Queens](#63-n-queens)
- [64. Subsets](#64-subsets)
- [65. Pascal's Triangle](#65-pascals-triangle)
- [66. House Robber II](#66-house-robber-ii)
- [67. Partition Equal Subset Sum](#67-partition-equal-subset-sum)
- [68. Number of Submatrices That Sum To Target](#68-number-of-submatrices-that-sum-to-target)
- [69. Shortest Path in Binary Matrix](#69-shortest-path-in-binary-matrix)
- [70.Validate Binary Search Tree](#70validate-binary-search-tree)
- [71. Reverse Nodes in k-Group](#71-reverse-nodes-in-k-group)
- [72. Trapping Rain Water](#72-trapping-rain-water)
- [73. Find Missing Positive](#73-find-missing-positive)
- [74. Edit Distance](#74-edit-distance)
- [75. Climbing Stairs](#75-climbing-stairs)
- [76. Shifting Letters II](#76-shifting-letters-ii)
- [77. Build A Matrix With Conditions](#77-build-a-matrix-with-conditions)
- [78. Serialize and Deserialize Binary Tree](#78-serialize-and-deserialize-binary-tree)
- [79. Pacific Atlantic Water Flow](#79-pacific-atlantic-water-flow)
- [80. Delete and Earn](#80-delete-and-earn)
- [81. Permutations II](#81-permutations-ii)
- [82. Combination Sum II](#82-combination-sum-ii)
- [83. Non Overlapping Intervals](#83-non-overlapping-intervals)
- [84. Best Time To Buy and Sell Stocks With Cooldown](#84-best-time-to-buy-and-sell-stocks-with-cooldown)
- [85. Maximum XOR of Two Numbers In An Array](#85-maximum-xor-of-two-numbers-in-an-array)
- [86. Implement Queue Using Stacks](#86-implement-queue-using-stacks)
- [87. Minimum Size Subarray Sum](#87-minimum-size-subarray-sum)
- [88. Number of Visible People In A Queue](#88-number-of-visible-people-in-a-queue)
- [89. Describe The Painting](#89-describe-the-painting)
- [90. Flood Fill](#90-flood-fill)
- [91. Palindrome Partitioning](#91-palindrome-partitioning)
- [92. Path With Maximum Gold](#92-path-with-maximum-gold)
- [93. Counting Bits](#93-counting-bits)
- [94. Word Break](#94-word-break)
- [95. Find Median From Data Stream](#95-find-median-from-data-stream)
- [96. Single Threaded CPU](#96-single-threaded-cpu)
- [97. Contiguous Array](#97-contiguous-array)
- [98. Falling Squares](#98-falling-squares)
- [99. Minimum XOR Sum of Two Arrays](#99-minimum-xor-sum-of-two-arrays)
- [100. Maximum Profit In Job Scheduling](#100-maximum-profit-in-job-scheduling)
- [101. Find Minimum Time To Finish All Jobs](#101-find-minimum-time-to-finish-all-jobs)
- [102. Course Schedule](#102-course-schedule)
- [103. Minimum Height Trees](#103-minimum-height-trees)
- [104. Russian Doll Envelopes](#104-russian-doll-envelopes)
- [105. Maximum AND Sum of Array](#105-maximum-and-sum-of-array)
- [106. Maximum Number of Robots Within Budget](#106-maximum-number-of-robots-within-budget)
- [107. Find Longest Awesome Substring](#107-find-longest-awesome-substring)
- [108. Maximum Rows Covered By Columns](#108-maximum-rows-covered-by-columns)
- [109. Create Sorted Array Through Instructions](#109-create-sorted-array-through-instructions)
- [110. Maximum Students Taking Exam](#110-maximum-students-taking-exam)
- [111. Number of Ways To Reach A Position After Exactly K Steps](#111-number-of-ways-to-reach-a-position-after-exactly-k-steps)
- [112. Find The Longest Substring Containing Vowels In Even Counts](#112-find-the-longest-substring-containing-vowels-in-even-counts)
- [113. Maximum Earnings From Taxi](#113-maximum-earnings-from-taxi)
- [114. Vertical Order Traversal Of A Binary Tree](#114-vertical-order-traversal-of-a-binary-tree)
- [115. Invert Binary Tree](#115-invert-binary-tree)
- [116. Count Primes](#116-count-primes)
- [117. Find The Shortest Superstring](#117-find-the-shortest-superstring)
- [118. Sum Root To Leaf Nodes](#118-sum-root-to-leaf-nodes)
- [119. Longest Common Subsequence](#119-longest-common-subsequence)
- [120. Count Number of Maximum Bitwise Or Subsets](#120-count-number-of-maximum-bitwise-or-subsets)
- [121. Jump Game III](#121-jump-game-iii)
- [122. Operations on Tree](#122-operations-on-tree)
- [123. Minimum Operations To Convert Number](#123-minimum-operations-to-convert-number)
- [124. Egg Drop With 2 Eggs and N Floors](#124-egg-drop-with-2-eggs-and-n-floors)
- [125. Time Needed To Inform All Employees](#125-time-needed-to-inform-all-employees)
- [126. Time Based Key-Value Store](#126-time-based-key-value-store)
- [127. Shortest Bridge](#127-shortest-bridge)
- [128. Flip String To Monotone Increasing](#128-flip-string-to-monotone-increasing)
- [129. Longest Increasing Subsequence - II](#129-longest-increasing-subsequence---ii)
- [130. Solving Questions With Brainpower](#130-solving-questions-with-brainpower)
- [131. Detonate The Maximum Bombs](#131-detonate-the-maximum-bombs)
- [132. Fair Distribution of Cookies](#132-fair-distribution-of-cookies)
- [133. Minimum Cost To Reach Destination In Time](#133-minimum-cost-to-reach-destination-in-time)
- [134. Longest Substring of One Repeating Character](#134-longest-substring-of-one-repeating-character)
- [135. Predict The Winner](#135-predict-the-winner)
- [136. Path With Minimum Effort](#136-path-with-minimum-effort)
- [137. Cheapest Flights Within K Stops](#137-cheapest-flights-within-k-stops)
- [138. Minimum Cost To Make at Least One Valid Path in Grid](#138-minimum-cost-to-make-at-least-one-valid-path-in-grid)
- [139. Frog Jump](#139-frog-jump)
- [140. Find Eventual Safe State](#140-find-eventual-safe-state)
- [141. No of Ways To Arrive At Destination](#141-no-of-ways-to-arrive-at-destination)
- [142. Sort List](#142-sort-list)
- [143. Frog Position After T Seconds](#143-frog-position-after-t-seconds)
- [144. Longest Zigzag Path In A Binary Tree](#144-longest-zigzag-path-in-a-binary-tree)
- [145. Balance A Binary Seach Tree](#145-balance-a-binary-seach-tree)
- [146. Linked List in Binary Tree](#146-linked-list-in-binary-tree)
- [147. Find Substring With Given Hash Value](#147-find-substring-with-given-hash-value)
- [148. Distinct Echo Substrings](#148-distinct-echo-substrings)
- [149. Longest Duplicate Substring](#149-longest-duplicate-substring)
- [150. Distribute Coins In Binary Tree](#150-distribute-coins-in-binary-tree)
- [151. Range Sum Query - Mutable](#151-range-sum-query---mutable)
- [152. Shortest Palindrome](#152-shortest-palindrome)
- [153. Maximum Number of Events That Can Be Attended](#153-maximum-number-of-events-that-can-be-attended)
- [154. Maximum Product of The Length of Two Palindromic Substrings](#154-maximum-product-of-the-length-of-two-palindromic-substrings)
- [155. Repeated DNA Sequences](#155-repeated-dna-sequences)
- [156. K Divisible Elements Subarray](#156-k-divisible-elements-subarray)
- [157. Problem Name](#157-problem-name)
## 1. Longest Increasing Subsequence
Solution - DP
```cpp
int lengthOfLIS(vector& nums) {
int N = nums.size();
vector dp;
for(int i = 0; i < N; i++) {
auto it = lower_bound(dp.begin(), dp.end(), nums[i]);
if(it != dp.end()) {
*it = nums[i];
} else {
dp.push_back(nums[i]);
}
}
return dp.size();
}
```
[⬆ Back to top](#table-of-contents)
## 2. Generate Parentheses
View Code
```cpp
class Solution {
public:
vector ans;
void backtracking(string &temp, int leftCnt, int rightCnt) {
// We found a valid parentheses.
if(leftCnt == 0 && rightCnt == 0) {
ans.push_back(temp);
return;
}
// Include left parentheses
if(leftCnt) {
temp += "(";
backtracking(temp, leftCnt - 1, rightCnt);
temp.pop_back();
}
// Include right parentheses
if(rightCnt > leftCnt) {
temp += ")";
backtracking(temp, leftCnt, rightCnt - 1);
temp.pop_back();
}
}
vector generateParenthesis(int n) {
string temp = "";
backtracking(temp, n, n);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 3. Sort Array By Parity
View Code
```cpp
vector sortArrayByParity(vector& A) {
sort(A.begin(), A.end(), [](int a, int b) {
return a % 2 < b % 2;
});
return A;
}
```
[⬆ Back to top](#table-of-contents)
## 4. Min Cost To Connect All Points
View Code
```cpp
class UnionFind {
private:
vector id, rank;
int cnt;
public:
UnionFind(int cnt) : cnt(cnt) {
id = vector(cnt);
rank = vector(cnt, 0);
for (int i = 0; i < cnt; ++i) id[i] = i;
}
int find(int p) {
if (id[p] == p) return p;
return id[p] = find(id[p]);
}
int getCount() {
return cnt;
}
bool connected(int p, int q) {
return find(p) == find(q);
}
void connect(int p, int q) {
int i = find(p), j = find(q);
if (i == j) return;
if (rank[i] < rank[j]) {
id[i] = j;
} else {
id[j] = i;
if (rank[i] == rank[j]) rank[j]++;
}
--cnt;
}
};
class Solution {
public:
int minCostConnectPoints(vector>& points) {
int N = points.size();
vector> E;
for(int i = 0; i < N; i++) {
for(int j = i + 1; j < N; j++) {
E.push_back({abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]), i, j});
}
}
UnionFind uf(N);
int ans = 0;
// How to convert vector into heap.
make_heap(E.begin(), E.end(), greater>());
while(uf.getCount() > 1) {
pop_heap(E.begin(), E.end(), greater>());
auto [w, u, v] = E.back();
E.pop_back();
if(uf.connected(u, v)) continue;
uf.connect(u, v);
ans += w;
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 5. Power(x, n)
View Code
```cpp
double recursion(double x, long n) {
if(n < 0) {
return 1 / recursion(x, -n);
}
if(n == 0) {
return 1;
}
if(n == 1) {
return x;
}
if(n == 2) {
return x * x;
}
return recursion( recursion (x, n / 2), 2) * (n % 2 ? x : 1);
}
double myPow(double x, int n) {
return recursion(x, (long)n);
}
```
[⬆ Back to top](#table-of-contents)
## 6. Critical Connections In A Network
View Code
```cpp
class Solution {
public:
vector> criticalConnections(int n, vector>& connections) {
vector ranks(n, INT_MIN);
vector> G(n), ans;
for(auto &e : connections) {
int u = e[0], v = e[1];
G[u].push_back(v);
G[v].push_back(u);
}
function dfs = [&](int u, int rank) {
if(ranks[u] >= 0) return ranks[u];
ranks[u] = rank;
int minRank = rank;
for(int v : G[u]) {
if(ranks[v] >= rank - 1) continue;
int neighbourMinRank = dfs(v, rank + 1);
minRank = min(minRank, neighbourMinRank);
if (neighbourMinRank > rank) {
ans.push_back({u, v});
}
}
return minRank;
};
dfs(0, 0);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 7. Longest Increasing Path In A Matrix
View Code
```cpp
class Solution {
public:
int M, N;
vector> cnt;
int dirs[4][2] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int dfs(vector> &A, int i, int j) {
if(cnt[i][j] != -1e9) {
return cnt[i][j];
}
cnt[i][j] = 1;
for(auto &dir : dirs) {
int a = i + dir[0];
int b = j + dir[1];
if(a < 0 || b < 0 || a >= M || b >= N || A[a][b] <= A[i][j]) continue;
cnt[i][j] = max(cnt[i][j] , 1 + dfs(A, a, b));
}
return cnt[i][j];
}
int longestIncreasingPath(vector>& matrix) {
M = matrix.size();
N = matrix[0].size();
cnt.assign(M, vector(N, -1e9));
int ans = 0;
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
ans = max(ans, dfs(matrix, i, j));
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 8. Valid Arrangement of Pairs
View Code
```cpp
class Solution {
public:
vector> validArrangement(vector>& pairs) {
unordered_map> G;
unordered_map indegrees, outdegrees;
for(auto &e : pairs) {
int u = e[0], v = e[1];
G[u].push_back(v);
indegrees[v]++;
outdegrees[u]++;
}
// Select the starting node.
int start = -1;
for(auto &[u, ad] : G ) {
if(outdegrees[u] - indegrees[u] == 1) {
start = u;
break;
}
}
if(start == -1) {
start = pairs[0][0];
}
vector> ans;
function euler = [&](int u) {
auto &ad = G[u];
while(ad.size()) {
int v = ad.back();
ad.pop_back();
euler(v);
ans.push_back({u, v});
}
};
euler(start);
reverse(ans.begin(), ans.end());
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 9. Next Greater Element II
View Code
```cpp
class Solution {
public:
vector nextGreaterElements(vector& nums) {
int N = nums.size();
// Stores index.
stack S;
// Stores element
vector ans(N, -1);
for(int i = 0; i < 2 * N; i++) {
int n = nums[i % N];
while(S.size() && nums[S.top()] < n) {
ans[S.top()] = n;
S.pop();
}
S.push(i % N);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 10. Container With Most Water
View Code
```cpp
class Solution {
public:
int maxArea(vector& height) {
int N = height.size();
int L = 0, R = N - 1;
int ans = 0;
while(L < R) {
int area = min(height[L], height[R]) * (R - L);
ans = max(ans, area);
if(height[L] < height[R]) {
L++;
} else {
R--;
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 11. Implement Trie (Prefix Tree)
View Code
```cpp
struct TrieNode {
TrieNode *next[26] = {};
bool word = false;
};
class Trie {
TrieNode root;
TrieNode *find(string s) {
auto node = &root;
for(char c : s) {
if(!node->next[c - 'a']) return NULL;
node = node->next[c - 'a'];
}
return node;
}
public:
void insert(string word) {
auto node = &root;
for(char c : word) {
if(!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->word = true;
}
bool search(string word) {
auto wordFind = find(word);
return wordFind && (wordFind->word == true);
}
bool startsWith(string prefix) {
return find(prefix);
}
};
```
[⬆ Back to top](#table-of-contents)
## 12. Sort The Matrix Diagonally
View Code
```cpp
class Solution {
public:
vector> diagonalSort(vector>& mat) {
int M = mat.size();
int N = mat[0].size();
for (int i = 0; i < M; ++i) {
vector v;
for (int x = i, y = 0; x < M && y < N; ++x, ++y) {
v.push_back(mat[x][y]);
}
sort(v.begin(), v.end());
int index = 0;
for (int x = i, y = 0; x < M && y < N; ++x, ++y) {
mat[x][y] = v[index++];
}
}
for (int j = 1; j < N; ++j) {
vector v;
for(int x = 0, y = j; x < M && y < N; ++x, ++y) {
v.push_back(mat[x][y]);
}
sort(v.begin(), v.end());
int index = 0;
for (int x = 0, y = j; x < M && y < N; ++x, ++y) {
mat[x][y] = v[index++];
}
}
return mat;
}
};
```
[⬆ Back to top](#table-of-contents)
## 13. Minimum Window Substring
View Code
```cpp
class Solution {
public:
string minWindow(string s, string t) {
unordered_map target, cnt;
int N = s.length();
// Store the frequency of target string
for(char c : t) {
target[c]++;
}
int matched = 0;
int start = 0, len = INT_MAX;
int i = 0;
// Traverse the s string, j - right boundary, left boundary - 0
for(int j = 0; j < N; j++) {
if(++cnt[s[j]] <= target[s[j]]) matched++;
// Target string comes inside this window substring.
while(matched == t.size()) {
// Update the answer start and its length
if(len > j - i + 1) {
len = j - i + 1;
start = i;
}
// Decrease the length of window.
if(--cnt[s[i]] < target[s[i]]) matched--;
i++;
}
}
if(len == INT_MAX) {
return "";
} else {
return s.substr(start, len);
}
}
};
```
[⬆ Back to top](#table-of-contents)
## 14. Increasing Triplet Subsequence
View Code
```cpp
class Solution {
public:
bool increasingTriplet(vector& nums) {
int N = nums.size();
vector dp;
for(int i = 0; i < N; i++) {
auto it = lower_bound(dp.begin(), dp.end(), nums[i]);
if(it != dp.end()) {
*it = nums[i];
} else {
dp.push_back(nums[i]);
}
}
return (dp.size() >= 3);
}
};
```
[⬆ Back to top](#table-of-contents)
## 15. Target Sum
Solution - Recursion (TLE)
```cpp
class Solution {
public:
int recur(vector& nums, int sum, int target, int i) {
int n = nums.size();
if(n == i) {
// Check the sum if it is equal to target
if(sum == target) return 1;
return 0;
}
int res = 0;
// Include
res += recur(nums, sum + nums[i], target, i + 1);
// Not Include
res += recur(nums, sum - nums[i], target, i + 1);
return res;
}
int findTargetSumWays(vector& nums, int target) {
// (vector, sum, target, index);
return recur(nums, 0, target, 0);
}
};
```
Solution - DP
```cpp
class Solution {
public:
int recursion(vector& nums, int sum, int target, int i, vector> &dp) {
if(i == nums.size()) {
return sum == target;
}
if(dp[i][sum + 1000] != -1) return dp[i][sum + 1000];
int include = recursion(nums, sum + nums[i], target, i + 1, dp);
int notInclude = recursion(nums, sum - nums[i], target, i + 1, dp);
dp[i][sum + 1000] = include + notInclude;
return dp[i][sum + 1000];
}
int findTargetSumWays(vector& nums, int target) {
vector> dp(nums.size() + 1, vector(3000, -1));
return recursion(nums, 0, target, 0, dp);
}
};
```
[⬆ Back to top](#table-of-contents)
## 16. Check If There Is A Valid Partition For The Array
View Code
```cpp
class Solution {
public:
bool validPartition(vector& nums) {
int N = nums.size();
bool dp[N + 1];
for(int i = 0; i <= N; i++) dp[i] = false;
dp[0] = true;
for(int i = 0; i < N; i++) {
// for two elements
if(i >= 1) {
if(dp[i - 1] && nums[i] == nums[i - 1]) {
dp[i + 1] = true;
}
}
// for three elements
if(i >= 2) {
if(dp[i - 2] && nums[i] == nums[i - 1] && nums[i - 1] == nums[i - 2]) {
dp[i + 1] = true;
}
}
// for three consecutive elements
if(i >= 2) {
if(dp[i - 2] && nums[i] == nums[i - 1] + 1 && nums[i - 1] == nums[i - 2] + 1) {
dp[i + 1] = true;
}
}
}
return dp[N];
}
};
```
[⬆ Back to top](#table-of-contents)
## 17. Longest Consecutive Sequence
View Code
```cpp
// Union Find that also return the vector of size of components.
class UnionFind {
vector id, size;
public:
UnionFind(int n) : id(n), size(n, 1) {
for (int i = 0; i < n; ++i) id[i] = i;
}
void connect(int a, int b) {
int x = find(a), y = find(b);
if (x == y) return;
id[x] = y;
size[y] += size[x];
}
int find(int a) {
return id[a] == a ? a : (id[a] = find(id[a]));
}
vector &getSizes() {
return size;
}
};
class Solution {
public:
int longestConsecutive(vector& nums) {
int N = nums.size();
if(N == 0) {
return 0;
}
UnionFind uf(N);
unordered_map M;
// We have to store indexes in UnionFind instead of integer values.
for(int i = 0; i < N; i++) {
int n = nums[i];
if(M.count(n)) continue;
M[n] = i;
if(M.count(n - 1)) uf.connect(M[n], M[n - 1]);
if(M.count(n + 1)) uf.connect(M[n], M[n + 1]);
}
// ans -> maximum component size
vector ans = uf.getSizes();
return *max_element(ans.begin(), ans.end());
}
};
```
[⬆ Back to top](#table-of-contents)
## 18. Valid Sudoku
View Code
```cpp
class Solution {
public:
bool isValidSudoku(vector>& board) {
int row[9][9] = {}, col[9][9] = {}, box[9][9] = {};
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
int n = board[i][j] - '1';
if(board[i][j] == '.') continue;
if(row[i][n] || col[j][n] || box[(i / 3) * 3 + (j / 3)][n]) return false;
row[i][n] = col[j][n] = box[i / 3 * 3 + j / 3][n] = 1;
}
}
return true;
}
};
```
[⬆ Back to top](#table-of-contents)
## 19. My Calendar I
View Code
```cpp
class MyCalendar {
public:
MyCalendar() {
}
map M;
bool book(int start, int end) {
if(M.empty()) {
M[start] = end;
return true;
}
// Conditions
auto it = M.upper_bound(start);
// Check the later intersection
if(it != M.end() && it->first < end) return false;
// Check the starting intersection
if(it != M.begin() && prev(it)->second > start) return false;
// After checking conditions
M[start] = end;
return true;
}
};
```
[⬆ Back to top](#table-of-contents)
## 20. Sliding Window Maximum
View Code
```cpp
class Solution {
public:
vector maxSlidingWindow(vector& nums, int k) {
int N = nums.size();
deque d; // Deque will store the index
vector ans;
for(int i = 0; i < N; i++) {
int n = nums[i];
// When the element goes out of window, remove from the deque.
if(d.size() && d.front() == i - k) d.pop_front();
// We have to store monotonically decreasing sequence.
while(d.size() && nums[d.back()] <= n) {
d.pop_back();
}
d.push_back(i);
if(i >= k - 1) {
// Push maximum element in answer.
ans.push_back(nums[d.front()]);
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 21. Best Time To Buy and Sell Stock
View Code
```cpp
class Solution {
public:
int maxProfit(vector& prices) {
int N = prices.size();
int minStock = prices[0];
int profit = 0;
for(int i = 0; i < N; i++) {
minStock = min(minStock, prices[i]);
profit = max(profit, prices[i] - minStock);
}
return profit;
}
};
```
[⬆ Back to top](#table-of-contents)
## 22. Maximum Subarray
View Code
```cpp
int maxSubArray(vector& nums) {
int global = nums[0];
int local = 0;
int N = nums.size();
for(int i = 0; i < N; i++) {
local = max(local + nums[i], nums[i]);
global = max(global, local);
}
return global;
}
```
[⬆ Back to top](#table-of-contents)
## 23. Cracking The Safe
View Code
```cpp
class Solution {
public:
string crackSafe(int n, int k) {
if(n == 1 && k == 1) return "0";
// Store the edges of graph.
unordered_set M;
string start = string(n - 1, '0');
string ans = "";
function euler = [&](string u) {
for(char c = '0'; c < k + '0'; c++) {
// How to use the last sequence optimally
string v = u + c;
// We don't have to visit the same edge again
if(M.count(v)) continue;
M.insert(v);
euler(v.substr(1));
ans.push_back(c);
}
};
euler(start);
return ans + start;
}
};
```
[⬆ Back to top](#table-of-contents)
## 24. Find If Path Exists In Graph
View Code
```cpp
class Solution {
public:
bool validPath(int n, vector>& edges, int source, int destination) {
// Creation of Graph
unordered_map> G;
for(auto &e : edges) {
int u = e[0], v = e[1];
G[u].push_back(v);
G[v].push_back(u);
}
// BFS
queue q;
vector seen(n, 0); // 0 ->unseen
q.push(source);
seen[source] = 1;
while(q.size()) {
int v = q.front();
q.pop();
// Traverse every edge of v in breadth first search
for(int u : G[v]) {
if(seen[u]) continue;
seen[u] = 1;
q.push(u);
}
}
if(seen[destination] == 1) {
return true;
} else {
return false;
}
}
};
```
[⬆ Back to top](#table-of-contents)
## 25. Next Greater Node In Linked List
View Code
```cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = new ListNode();
while(head) {
auto node = head;
head = head->next;
node->next = prev->next;
prev->next = node;
}
return prev->next;
}
vector nextLargerNodes(ListNode* head) {
head = reverseList(head);
stack S;
vector ans;
while(head) {
int n = head->val;
while(S.size() && S.top() <= n) {
S.pop();
}
if(S.size() == 0) {
ans.push_back(0);
} else {
ans.push_back(S.top());
}
S.push(n);
head = head->next;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 26. Repeated Substring Pattern
View Code
```cpp
class Solution {
public:
bool repeatedSubstringPattern(string s) {
int N = s.length();
for(int len = 1; len <= N / 2; len++) {
if(N % len) continue;
int i = len;
for(; i < N; i++) {
if( s[i] != s[i % len]) break;
}
if(i == N) return true;
}
return false;
}
};
```
[⬆ Back to top](#table-of-contents)
## 27. Search Suggestion System
View Code
```cpp
struct TrieNode {
TrieNode *next[26] = {};
int index = -1;
};
void add(TrieNode *node, string &s, int i) {
for(char c: s) {
if(!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->index = i;
}
void collect(TrieNode *node, vector &ans, vector &products) {
if(ans.size() == 3) return;
if(!node) return;
if(node->index > -1) ans.push_back(products[node->index]);
for(int i = 0; i < 26; i++) {
if(node->next[i]) collect(node->next[i], ans, products);
}
}
class Solution {
public:
vector> suggestedProducts(vector& products, string searchWord) {
TrieNode root, *node = &root;
for(int i = 0; i < products.size(); i++) {
add(&root, products[i], i);
}
vector> ans(searchWord.size());
for(int i = 0; i < searchWord.length(); i++) {
node = node->next[searchWord[i] - 'a'];
if(!node) break;
collect(node, ans[i], products);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 28. Merge K Sorted Lists
View Code
```cpp
class Solution {
public:
ListNode* mergeKLists(vector& lists) {
ListNode dummy, *tail = &dummy;
auto cmp = [](auto a, auto b) { return a->val > b->val; };
priority_queue, decltype(cmp)> q(cmp);
for (auto list : lists) {
if (list) q.push(list); // avoid pushing NULL list.
}
while (q.size()) {
auto node = q.top();
q.pop();
if (node->next) q.push(node->next);
tail->next = node;
tail = node;
}
return dummy.next;
}
};
```
[⬆ Back to top](#table-of-contents)
## 29. Daily Temperatures
View Code
```cpp
class Solution {
public:
vector dailyTemperatures(vector& A) {
stack s;
vector ans(A.size());
for (int i = A.size() - 1; i >= 0; --i) {
while (s.size() && A[s.top()] <= A[i]) s.pop();
ans[i] = s.size() ? s.top() - i : 0;
s.push(i);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 30. Merge Intervals
View Code
```cpp
class Solution {
public:
vector> merge(vector>& intervals) {
sort(intervals.begin(), intervals.end());
vector> ans;
for(auto &a : intervals) {
if(!ans.size() || a[0] > ans.back()[1]) {
ans.push_back(a);
} else if(ans.back()[1] < a[1]) {
ans.back()[1] = a[1];
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 31. Word Ladder
View Code
```cpp
int ladderLength(string beginWord, string endWord, vector& wordList) {
unordered_set s(begin(wordList), end(wordList));
if (s.count(endWord) == 0) return 0;
queue q{{beginWord}};
s.erase(beginWord);
int step = 1;
while (q.size()) {
int cnt = q.size();
while (cnt--) {
auto u = q.front();
q.pop();
if (u == endWord) return step;
for (char &c : u) { // add unvisited neighbors of `u`
char tmp = c;
for (char ch = 'a'; ch <= 'z'; ++ch) {
if (tmp == ch) continue;
c = ch;
if (s.count(u) == 0) continue;
s.erase(u);
q.push(u);
}
c = tmp;
}
}
++step;
}
return 0;
}
```
[⬆ Back to top](#table-of-contents)
## 32. 3Sum
View Code
```cpp
vector> threeSum(vector& A) {
vector> ans;
sort(A.begin(), A.end());
int N = A.size();
int L = 0, R = N - 1;
for(int i = 0; i < N - 2; i++) {
if(i > 0 && A[i] == A[i - 1]) continue;
int L = i + 1, R = N - 1;
while(L < R) {
int sum = A[i] + A[L] + A[R];
if(sum == 0) {
ans.push_back({A[i], A[L], A[R]});
}
if(sum <= 0) {
L++;
while(L < R && A[L] == A[L - 1]) L++;
}
if(sum >= 0) {
R--;
while(L < R && A[R] == A[R + 1]) R--;
}
}
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 33. Flatten Binary Tree To Linked List
View Code
```cpp
void flatten(TreeNode* root) {
if(!root) return;
TreeNode *tail = nullptr;
stack S;
S.push({root});
while(S.size()) {
auto node = S.top();
S.pop();
if(tail) tail->right = node;
tail = node;
if(node->right) S.push(node->right);
if(node->left) S.push(node->left);
node->left = node->right = nullptr;
}
}
```
[⬆ Back to top](#table-of-contents)
## 34. Sum of Subarray Minimums
View Code
```cpp
int sumSubarrayMins(vector& A) {
stack q;
q.push(-1);
long N = A.size(), ans = 0, sum = 0, mod = 1e9+7;
for (int i = 0; i < N; ++i) {
sum = (sum + A[i]) % mod;
while (q.top() != -1 && A[q.top()] >= A[i]) {
int j = q.top();
q.pop();
int c = j - q.top();
sum = (sum + c * (A[i] - A[j]) % mod) % mod;
}
q.push(i);
ans = (ans + sum) % mod;
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 35. Median of Two Sorted Arrays
View Code
```cpp
double findMedianSortedArrays(vector& nums1, vector& nums2) {
if (nums1.size() > nums2.size()) swap(nums1, nums2);
int M = nums1.size(), N = nums2.size(), L = 0, R = M, K = (M + N + 1) / 2;
while (true) {
int i = (L + R) / 2, j = K - i;
if (i < M && nums2[j - 1] > nums1[i]) L = i + 1;
else if (i > L && nums1[i - 1] > nums2[j]) R = i - 1;
else {
int maxLeft = max(i ? nums1[i - 1] : INT_MIN, j ? nums2[j - 1] : INT_MIN);
if ((M + N) % 2) return maxLeft;
int minRight = min(i == M ? INT_MAX : nums1[i], j == N ? INT_MAX : nums2[j]);
return (maxLeft + minRight) / 2.0;
}
}
}
```
[⬆ Back to top](#table-of-contents)
## 36. LRU Cache
View Code
```cpp
class LRUCache {
int capacity;
list> data;
unordered_map>::iterator> m;
void moveToFront(int key) {
auto node = m[key];
data.splice(data.begin(), data, node);
m[key] = data.begin();
}
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key) {
// get node given key, put the node at the beginning of the list, return the value in the node
if (m.count(key)) {
moveToFront(key);
return m[key]->second;
}
return -1;
}
void put(int key, int value) {
// if key exists in the map, get node given key, put the node at the beginning of the list and update the value in the node
// otherwise, put a new node at the beginning of the list with the and update the map. If capacity exceeded, remove the last node from the list and map.
if (m.count(key)) {
moveToFront(key);
m[key]->second = value;
} else {
data.emplace_front(key, value);
m[key] = data.begin();
if (data.size() > capacity) {
m.erase(data.rbegin()->first);
data.pop_back();
}
}
}
};
```
[⬆ Back to top](#table-of-contents)
## 37. Gas Station
View Code
```cpp
int canCompleteCircuit(vector& gas, vector& cost) {
int N = gas.size(), len = 0, start = 0;
for (int i = 0, sum = 0; i < 2 * N && len < N; ++i) {
sum += gas[i % N] - cost[i % N];
if (sum < 0) {
len = sum = 0;
start = (i + 1) % N;
} else ++len;
}
return len == N ? start : -1;
}
```
[⬆ Back to top](#table-of-contents)
## 38. Max Points On A Line
View Code
```cpp
class Solution {
public:
int maxPoints(vector>& points) {
int res = 0;
for(int i = 0; i noOfPointsInLine;
for(int j = i + 1; j < points.size(); j++){
int x1 = points[i][0], y1 = points[i][1], x2 = points[j][0], y2 = points[j][1];
if(y2 == y1) {
noOfPointsInLine[INT_MIN]++;
} else if(x1 == x2){
noOfPointsInLine[INT_MAX]++;
} else {
long double slope = (long double)(y2 - y1) /(long double)(x2 - x1);
noOfPointsInLine[slope]++;
}
}
for(auto i : noOfPointsInLine){
res = max(i.second, res);
}
}
return res + 1;
}
};
```
[⬆ Back to top](#table-of-contents)
## 39. Largest Rectangle In Histogram
View Code
```cpp
class Solution {
public:
int largestRectangleArea(vector& A) {
int N = A.size();
int ans = 0;
stack S;
vector next(N, N), prev(N, -1);
for(int i = 0; i < N; i++) {
while(S.size() && A[i] < A[S.top()]) {
next[S.top()] = i;
S.pop();
}
S.push(i);
}
for(int i = N - 1; i >= 0; i--) {
while(S.size() && A[i] < A[S.top()]) {
prev[S.top()] = i;
S.pop();
}
S.push(i);
}
for(int i = 0; i < N; i++) {
ans = max(ans, A[i] * (next[i] - prev[i] - 1));
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 40. Regular Expression Matching
View Code
```cpp
class Solution {
private:
inline bool matchChar(string &s, int i, string &p, int j) {
return p[j] == '.' ? i < s.size() : s[i] == p[j];
}
bool isMatch(string s, int i, string p, int j) {
if (j == p.size()) return i == s.size();
if (j + 1 < p.size() && p[j + 1] == '*') {
bool ans = false;
while (!(ans = isMatch(s, i, p, j + 2))
&& matchChar(s, i, p, j)) ++i;
return ans;
} else {
return matchChar(s, i, p, j) && isMatch(s, i + 1, p, j + 1);
}
}
public:
bool isMatch(string s, string p) {
return isMatch(s, 0, p, 0);
}
};
```
[⬆ Back to top](#table-of-contents)
## 41. Minimum Deletions To Make Character Frequencies Unique
View Code
```cpp
class Solution {
public:
int minDeletions(string s) {
int cnt[26] = {0};
set S;
int ans = 0;
for (char c : s) {
cnt[c - 'a']++;
}
for(int i = 0; i < 26; i++) {
while(cnt[i]-- && !S.insert(cnt[i]).second) {
ans++;
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 42. Jump Game II
View Code
```cpp
class Solution {
public:
int jump(vector& nums) {
int N = nums.size();
vector dp(N, 1e9);
dp[0] = 0;
for(int i = 0; i < N; i++) {
for(int j = 1; j <= nums[i] && i + j < N; j++) {
dp[i + j] = min(dp[i + j], 1 + dp[i]);
}
}
return dp[N - 1];
}
};
```
[⬆ Back to top](#table-of-contents)
## 43. Count Good Nodes In Binary Tree
View Code
```cpp
class Solution {
public:
int ans = 0;
int dfs(TreeNode* root, int maxVal) {
if(root->val >= maxVal) {
ans++;
}
maxVal = max(maxVal, root->val);
if(root->left) {
dfs(root->left, maxVal);
}
if(root->right) {
dfs(root->right, maxVal);
}
return ans;
}
int goodNodes(TreeNode* root) {
return dfs(root, INT_MIN);
}
};
```
[⬆ Back to top](#table-of-contents)
## 44. Unique Paths
View Code
```cpp
class Solution {
public:
int uniquePaths(int m, int n) {
vector dp(n + 1, 0);
dp[n - 1] = 1;
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--){
dp[j] += dp[j + 1];
}
}
return dp[0];
}
};
```
[⬆ Back to top](#table-of-contents)
## 45. Coin Change
View Code
```cpp
class Solution {
public:
int coinChange(vector& coins, int amount) {
int dp[amount + 1];
dp[0] = 0;
sort(coins.begin(), coins.end());
for(int i = 1; i <= amount; i++) {
dp[i] = INT_MAX;
for(auto &coin : coins) {
if(i - coin < 0) break;
if(dp[i - coin] != INT_MAX) {
dp[i] = min(dp[i], 1 + dp[i - coin]);
}
}
}
if(dp[amount] != INT_MAX) {
return dp[amount];
} else {
return -1;
}
}
};
```
[⬆ Back to top](#table-of-contents)
## 46. Is Graph Bipartite ?
View Code
```cpp
class Solution {
public:
bool isBipartite(vector>& G) {
int N = G.size();
vector id(N); // 0 unseen, 1 and -1 are different colors
function dfs = [&](int u, int color) {
if (id[u]) return id[u] == color;
id[u] = color;
for (int v : G[u]) {
if (!dfs(v, -color)) return false;
}
return true;
};
for (int i = 0; i < N; ++i) {
if (!id[i] && !dfs(i, 1)) return false;
}
return true;
}
};
```
[⬆ Back to top](#table-of-contents)
## 47. Frequency of Most Frequent Elements
View Code
```cpp
class Solution {
public:
int maxFrequency(vector& A, int k) {
int N = A.size();
sort(A.begin(), A.end());
long ans = 1, sum = 0, i = 0;
for(int j = 0; j < N; j++) {
sum += A[j];
// Increase the left boundary of window :
// (Length of window * currentElement) - Sum of all elements > k
while( (j - i + 1) * A[j] - sum > k) {
sum -= A[i++];
}
ans = max(ans, j - i + 1);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 48. Group Anagrams
View Code
```cpp
class Solution {
public:
vector> groupAnagrams(vector& strs) {
unordered_map> M;
for(string &s : strs) {
string t = s;
sort(t.begin(), t.end());
M[t].push_back(s);
}
vector> ans;
for(auto &[s, vs] : M) {
ans.push_back(vs);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 49. Satisfiability of Equality Equations
View Code
```cpp
class UnionFind {
private:
vector id, rank;
int cnt;
public:
UnionFind(int cnt) : cnt(cnt) {
id = vector(cnt);
rank = vector(cnt, 0);
for (int i = 0; i < cnt; ++i) id[i] = i;
}
int find(int p) {
if (id[p] == p) return p;
return id[p] = find(id[p]);
}
int getCount() {
return cnt;
}
bool connected(int p, int q) {
return find(p) == find(q);
}
void connect(int p, int q) {
int i = find(p), j = find(q);
if (i == j) return;
if (rank[i] < rank[j]) {
id[i] = j;
} else {
id[j] = i;
if (rank[i] == rank[j]) rank[j]++;
}
--cnt;
}
};
class Solution {
public:
bool equationsPossible(vector& equations) {
int N = equations.size();
UnionFind uf(26);
for(auto &e : equations) {
if(e[1] == '=') {
int num1 = e[0] - 'a';
int num2 = e[3] - 'a';
uf.connect(num1, num2);
}
}
for(auto &e : equations) {
if(e[1] == '!') {
int num1 = e[0] - 'a';
int num2 = e[3] - 'a';
if(uf.connected(num1, num2)) {
return false;
}
}
}
return true;
}
};
```
[⬆ Back to top](#table-of-contents)
## 50. Range Sum BST
View Code
```cpp
class Solution {
public:
int sum = 0;
void preorder(TreeNode* root, int L, int R) {
if(!root) {
return;
}
if(root->val >= L && root->val <= R) {
sum += root->val;
}
preorder(root->left, L, R);
preorder(root->right, L, R);
}
int rangeSumBST(TreeNode* root, int low, int high) {
preorder(root, low, high);
return sum;
}
};
```
[⬆ Back to top](#table-of-contents)
## 51. Number of Islands
View Code
```cpp
class Solution {
public:
int M, N;
int dirs[4][2] = { {0, 1}, {1, 0}, {-1, 0}, {0, -1}};
void dfs(vector> &grid, int i, int j) {
// This cell of grid has been visited.
grid[i][j] = '2';
// Go to the four sides of grid.
for(auto &dir : dirs) {
int a = i + dir[0];
int b = j + dir[1];
if(a < 0 || b < 0 || a >= M || b >= N || grid[a][b] != '1') continue;
dfs(grid, a, b);
}
}
int numIslands(vector>& grid) {
M = grid.size();
N = grid[0].size();
int islandCnt = 0;
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(grid[i][j] == '1') {
dfs(grid, i, j);
islandCnt++;
}
}
}
return islandCnt;
}
};
```
[⬆ Back to top](#table-of-contents)
## 52. Wildcard Matching
View Code
```cpp
class Solution {
public:
int M, N;
vector> dp;
bool wildcardMatching(string &s, string &p, int i, int j) {
if(dp[i][j] != -1) return dp[i][j];
int &ans = dp[i][j];
for(; j < N; j++) {
if(p[j] != '*' && i >= M) return ans = false;
if(p[j] == '?') {
i++;
} else if(p[j] == '*') {
while(j + 1 < N && p[j + 1] == '*') j++;
for(int k = 0; i + k <= M; i++) {
if(wildcardMatching(s, p, i + k, j + 1)) {
return ans = true;
}
}
} else if(s[i++] != p[j]) {
return ans = false;
}
}
return ans = i >= M;
}
bool isMatch(string s, string p) {
M = s.size();
N = p.size();
dp.assign(M + 1, vector(N + 1, -1));
return wildcardMatching(s, p, 0, 0);
}
};
```
[⬆ Back to top](#table-of-contents)
## 53. Min Stack
View Code
```cpp
class MinStack {
public:
stack S, M;
void push(int val) {
S.push(val);
if(M.empty() || M.top() >= val) {
M.push(val);
}
}
void pop() {
int x = S.top();
S.pop();
// If popped element is minimum
if(M.top() == x) {
M.pop();
}
}
int top() {
return S.top();
}
int getMin() {
return M.top();
}
};
```
[⬆ Back to top](#table-of-contents)
## 54. Permutations
View Code
```cpp
class Solution {
public:
vector> ans;
void permute(vector &nums, int start) {
// Base case
if(start == nums.size()) {
ans.push_back(nums);
return;
}
for(int i = start; i < nums.size(); i++) {
swap(nums[start], nums[i]);
permute(nums, start + 1);
swap(nums[start], nums[i]);
}
}
vector> permute(vector& nums) {
permute(nums, 0);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 55. Combinations
View Code
```cpp
class Solution {
public:
vector> ans;
void combine(vector &temp, int n, int k, int start) {
// Base case
if(temp.size() == k) {
ans.push_back(temp);
return;
}
for(int i = start, end = n - k + temp.size(); i <= end; i++) {
temp.push_back(i + 1);
combine(temp, n, k, i + 1);
temp.pop_back();
}
}
vector> combine(int n, int k) {
vector temp;
combine(temp, n, k, 0);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 56. Diameter of Binary Tree
View Code
```cpp
class Solution {
public:
int diameter = 0;
int dfs(TreeNode* root) {
if(!root) {
return 0;
}
int left = dfs(root->left);
int right = dfs(root->right);
diameter = max(diameter, left + right);
return (1 + max(left, right));
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return diameter;
}
};
```
[⬆ Back to top](#table-of-contents)
## 57. Peak Index In Mountain Array
View Code
```cpp
int peakIndexInMountainArray(vector& arr) {
int N = arr.size();
int L = 1, R = N - 2, M;
while(L <= R) {
M = (L + R) / 2;
if(arr[M] > arr[M - 1]) {
L = M + 1;
} else {
R = M - 1;
}
}
return R;
}
```
[⬆ Back to top](#table-of-contents)
## 58. Maximum Depth of Binary Tree
View Code
```cpp
int maxDepth(TreeNode* root) {
if(!root) {
return 0;
}
return (1 + max(maxDepth(root->left), maxDepth(root->right)));
}
```
[⬆ Back to top](#table-of-contents)
## 59. Find Minimum In Rotated Sorted Array
View Code
```cpp
int findMin(vector& nums) {
int N = nums.size();
int L = 0, R = N - 1, M;
while(L < R) {
M = (L + R) / 2;
if(nums[M] < nums[R]) {
R = M;
} else {
L = M + 1;
}
}
return nums[R];
}
```
[⬆ Back to top](#table-of-contents)
## 60. Binary Tree Zigzag Level Order Traversal
View Code
```cpp
class Solution {
public:
vector> ans;
vector> zigzagLevelOrder(TreeNode* root) {
if(!root) {
return {};
}
bool l2r = true;
queue q;
q.push({root});
while(q.size()) {
int cnt = q.size();
vector temp;
while(cnt--) {
auto node = q.front();
q.pop();
temp.push_back(node->val);
if(node->left) {
q.push(node->left);
}
if(node->right) {
q.push(node->right);
}
}
if(!l2r) {
reverse(temp.begin(), temp.end());
}
l2r = !l2r;
ans.push_back(temp);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 61. Longest Substring Without Repeating Characters
View Code
```cpp
int lengthOfLongestSubstring(string s) {
int N = s.length();
int length = 0, i = 0;
unordered_map M;
for(int j = 0; j < N; j++) {
M[s[j]]++;
// Increase the window size from left side if there are multiple characters
while(M[s[j]] > 1) {
M[s[i++]]--;
}
length = max(length, j - i + 1);
}
return length;
}
```
[⬆ Back to top](#table-of-contents)
## 62. Combination Sum
View Code
```cpp
vector> combinationSum(vector& A, int target) {
vector> ans;
vector tmp;
sort(begin(A), end(A));
function dfs = [&](int start, int goal) {
if (goal == 0) {
ans.push_back(tmp);
}
for (int i = start; i < A.size() && gaol - A[i] >= 0; ++i) {
tmp.push_back(A[i]);
dfs(i, goal - A[i]);
tmp.pop_back();
}
};
dfs(0, target);
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 63. N-Queens
View Code
```cpp
class Solution {
public:
vector> ret;
bool is_valid(vector &board, int row, int col) {
for(int i = row; i >= 0; --i) {
if(board[i][col] == 'Q') return false;
}
for(int i = row, j = col; i >= 0 && j >= 0; --i, --j) {
if(board[i][j] == 'Q') return false;
}
for(int i = row, j = col; i >= 0 && j < board.size(); --i, ++j) {
if(board[i][j] == 'Q') return false;
}
return true;
}
void dfs(vector &board, int row){
if(row == board.size()){
ret.push_back(board);
return;
}
for(int i=0; i < board.size(); ++i) {
if(is_valid(board, row, i)){
board[row][i] = 'Q';
dfs(board, row + 1);
board[row][i] = '.';
}
}
}
vector> solveNQueens(int n) {
vectorboard(n, string(n, '.'));
dfs(board, 0);
return ret;
}
};
```
[⬆ Back to top](#table-of-contents)
## 64. Subsets
View Code
```cpp
vector> subsets(vector& A) {
vector> ans;
vector tmp;
function dfs = [&](int i) {
if (i == A.size()) {
ans.push_back(tmp);
return;
}
tmp.push_back(A[i]);
dfs(i + 1); // Pick A[i]
tmp.pop_back();
dfs(i + 1); // Skip A[i]
};
dfs(0);
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 65. Pascal's Triangle
View Code
```cpp
vector> generate(int numRows) {
vector> ans(numRows);
for (int i = 0; i < numRows; ++i) {
ans[i] = vector(i + 1, 1);
for (int j = 1; j < i; ++j) ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 66. House Robber II
View Code
```cpp
class Solution {
public:
int rob(vector& nums) {
int N = nums.size();
if(N == 1) return nums[0];
if(N == 2) return max(nums[0], nums[1]);
return max(robber(nums, 0, N - 2), robber(nums, 1, N - 1));
}
int robber(vector &nums, int l, int r) {
int pre = 0, cur = 0;
for(int i = l; i <= r; i++) {
int temp = max(pre + nums[i], cur);
pre = cur;
cur = temp;
}
return cur;
}
};
```
[⬆ Back to top](#table-of-contents)
## 67. Partition Equal Subset Sum
View Code
```cpp
class Solution {
public:
vector> dp;
bool recurse(vector& nums, int i, int target, vector> &dp) {
if(i >= nums.size()) {
return false;
}
if(target <= 0) {
return target == 0;
}
if(dp[i][target] != -1) {
return dp[i][target];
}
return dp[i][target] = (recurse(nums, i + 1, target - nums[i], dp) || recurse(nums, i + 1, target, dp));
}
bool canPartition(vector& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0);
if(sum % 2) return false;
sum /= 2;
dp.assign(nums.size() + 1, vector(sum + 1, -1));
return recurse(nums, 0, sum, dp);
}
};
```
[⬆ Back to top](#table-of-contents)
## 68. Number of Submatrices That Sum To Target
View Code
```cpp
class Solution {
public:
int numSubmatrixSumTarget(vector>& matrix, int target) {
int M = matrix.size(), N = matrix[0].size(), ans = 0;
vector> sum(M + 1, vector(N + 1, 0));
for (int i = 1; i <= M; ++i) {
for (int j = 1; j <= N; ++j) {
sum[i][j] = sum[i][j - 1] + sum[i - 1][j] - sum[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j <= N; ++j) {
unordered_map m {{ 0, 1 }};
for (int k = 1; k <= M; ++k) {
int val = sum[k][j] - sum[k][i];
ans += m[val - target];
m[val]++;
}
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 69. Shortest Path in Binary Matrix
View Code
```cpp
class Solution {
public:
int dirs[8][2] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
int shortestPathBinaryMatrix(vector>& G) {
if (G[0][0] == 1) return -1;
int N = G.size();
vector> dist(N, vector(N, INT_MAX));
queue> q;
q.emplace(0, 0);
dist[0][0] = 1;
while (q.size()) {
auto [x, y] = q.front();
q.pop();
for(int i = 0; i < 8; i++) {
int a = x + dirs[i][0];
int b = y + dirs[i][1];
if (a < 0 || a >= N || b < 0 || b >= N || G[a][b] == 1 || dist[a][b] != INT_MAX) continue;
dist[a][b] = dist[x][y] + 1;
q.emplace(a, b);
}
}
return dist[N - 1][N - 1] == INT_MAX ? -1 : dist[N - 1][N - 1];
}
};
```
[⬆ Back to top](#table-of-contents)
## 70.Validate Binary Search Tree
View Code
```cpp
class Solution {
public:
bool isValidBST(TreeNode* root, TreeNode* left = NULL, TreeNode* right = NULL) {
if(!root) {
return true;
}
if(left && root->val <= left->val || right && root->val >= right->val) {
return false;
}
return (isValidBST(root->left, left, root) && isValidBST(root->right, root, right));
}
};
```
[⬆ Back to top](#table-of-contents)
## 71. Reverse Nodes in k-Group
View Code
```cpp
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode h, *tail = &h;
while (head) {
auto prev = tail;
int i = 0;
for (auto p = head; i < k && p; ++i, p = p->next);
if (i < k) {
tail->next = head;
break;
}
for (int i = 0; i < k && head; ++i) {
auto node = head;
head = head->next;
node->next = prev->next;
prev->next = node;
}
while (tail->next) tail = tail->next;
}
return h.next;
}
};
```
[⬆ Back to top](#table-of-contents)
## 72. Trapping Rain Water
View Code
```cpp
class Solution {
public:
int trap(vector& A) {
int N = A.size(), ans = 0;
vector left(N, 0), right(N, 0);
for (int i = 1; i < N; ++i) left[i] = max(left[i - 1], A[i - 1]);
for (int i = N - 2; i >= 0; --i) right[i] = max(right[i + 1], A[i + 1]);
for (int i = 1; i < N - 1; ++i) ans += max(0, min(left[i], right[i]) - A[i]);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 73. Find Missing Positive
View Code
```cpp
int firstMissingPositive(vector& A) {
int i, N = A.size();
for (i = 0; i < N; ) {
if (A[i] == i + 1 || A[i] < 1 || A[i] >= N + 1 || A[i] == A[A[i] - 1]) ++i;
else swap(A[i], A[A[i] - 1]);
}
for (i = 0; i < N && A[i] == i + 1; ++i);
return i + 1;
}
int firstMissingPositive(vector& nums) {
int N = nums.size();
// Ignore negatives and zero.
for(int i = 0; i < N; i++) if(nums[i] <= 0) nums[i] = N + 1;
// Replacing numbers with their negatives
for(int i = 0; i < N; i++) {
if(abs(nums[i]) <= N && nums[abs(nums[i]) - 1] > 0) {
nums[abs(nums[i]) - 1] *= -1;
}
}
for(int i = 0; i < N; i++) {
if(nums[i] > 0) {
return i + 1;
}
}
return N + 1;
}
```
[⬆ Back to top](#table-of-contents)
## 74. Edit Distance
View Code
```cpp
class Solution {
public:
int minDistance(string word1, string word2) {
int M = word1.size();
int N = word2.size();
if(!M) return N;
if(!N) return M;
vector> dp(M + 1, vector(N + 1, INT_MAX));
dp[0][0] = 0;
for(int i = 0; i < M; i++) {
dp[i + 1][0] = i + 1;
}
for(int j = 0; j < N; j++) {
dp[0][j + 1] = j + 1;
}
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(word1[i] == word2[j]) {
dp[i + 1][j + 1] = dp[i][j];
} else {
dp[i + 1][j + 1] = 1 + min({dp[i][j], dp[i + 1][j], dp[i][j + 1]});
}
}
}
return dp[M][N];
}
};
```
[⬆ Back to top](#table-of-contents)
## 75. Climbing Stairs
View Code
```cpp
int climbStairs(int n) {
int prev = 0, cur = 1;
while (n--) {
int next = cur + prev;
prev = cur;
cur = next;
}
return cur;
}
```
[⬆ Back to top](#table-of-contents)
## 76. Shifting Letters II
View Code
```cpp
// Solution 1 - Line Sweep
string shiftingLetters(string s, vector>& shifts) {
int line[50001] = {};
for (auto &shift : shifts) {
line[shift[0]] += shift[2] ? 1 : -1;
line[shift[1] + 1] += shift[2] ? -1 : 1;
}
for (int i = 0, val = 0; i < s.size(); ++i) {
val = (val + line[i]) % 26;
s[i] = 'a' + (26 + (s[i] - 'a') + val) % 26;
}
return s;
}
// Solution 2 - Fenwick Tree
constexpr int static n = 50000;
int bt[n + 1] = {};
int prefix_sum(int i)
{
int sum = 0;
for (i = i + 1; i > 0; i -= i & (-i))
sum += bt[i];
return sum;
}
void add(int i, int val)
{
for (i = i + 1; i <= n; i += i & (-i))
bt[i] += val;
}
string shiftingLetters(string s, vector>& shifts) {
for (auto &shift : shifts) {
add(shift[0], shift[2] == 1 ? 1 : -1);
add(shift[1] + 1, shift[2] == 1 ? -1 : 1);
}
for (int i = 0; i < s.size(); ++i)
s[i] = 'a' + (26 + (s[i] - 'a') + prefix_sum(i) % 26) % 26;
return s;
}
// Solution 3 - Segment Tree
class Solution {
public:
vector seg;
void upd(int l, int r, int v, int x, int lx, int rx) {
if(lx > r or rx < l) return;
if(lx >= l and rx <= r) {
seg[x] += v;
return;
}
int mid = (lx + rx) / 2;
upd(l, r, v, 2 * x + 1, lx, mid);
upd(l, r, v, 2 * x + 2, mid + 1, rx);
}
int query(int i, int x, int lx, int rx) {
if(lx == rx) return seg[x];
int mid = (lx + rx) / 2;
if(i <= mid)
return seg[x] + query(i, 2 * x + 1, lx, mid);
return seg[x] + query(i, 2 * x + 2, mid + 1, rx);
}
string shiftingLetters(string s, vector>& shifts) {
long x = 1;
while(x <= s.length()) x <<= 1;
seg.resize(2 * x, 0);
for(int i = 0; i < shifts.size(); ++i) {
int l = shifts[i][0], r = shifts[i][1], dir;
if(shifts[i][2] == 0) dir = -1;
else dir = 1;
upd(l, r, dir, 0, 0, x - 1);
}
for(int i = 0; i < s.length(); ++i) {
int shift = query(i, 0, 0, x - 1);
int dir = (shift > 0) ? 1 : -1;
shift = abs(shift) % 26;
shift *= dir;
int cur = s[i] - 'a';
cur = (cur + shift + 26) % 26;
s[i] = char(cur + 'a');
}
return s;
}
};
```
[⬆ Back to top](#table-of-contents)
## 77. Build A Matrix With Conditions
View Code
```cpp
vector> buildMatrix(int k, vector>& rowConditions, vector>& colConditions) {
vector order1 = topologicalSort(rowConditions, k);
vector order2 = topologicalSort(colConditions, k);
if (order1.size() < k || order2.size() < k) return {};
unordered_map m;
for (int i = 0; i < k; i++) m[order2[i]] = i;
vector> ans(k, vector(k, 0));
for (int i = 0; i < k; i++)
ans[i][m[order1[i]]] = order1[i];
return ans;
}
vector topologicalSort(vector> &A, int k) {
vector deg(k, 0), order;
vector> graph(k, vector(0));
queue q;
for (auto &c: A) {
graph[c[0] - 1].push_back(c[1] - 1);
deg[c[1] - 1]++;
}
for(int i = 0; i < k; i++)
if (!deg[i]) q.push(i);
while (!q.empty()) {
int x = q.front(); q.pop();
order.push_back(x + 1);
for (int& y: graph[x])
if (--deg[y] == 0)
q.push(y);
}
return order;
}
```
[⬆ Back to top](#table-of-contents)
## 78. Serialize and Deserialize Binary Tree
View Code
```cpp
class Codec {
private:
TreeNode *getNode(vector &v, int &i) {
string s = v[i++];
return s == "#" ? NULL : new TreeNode(stoi(s));
}
public:
string serialize(TreeNode* root) {
if (!root) return "";
queue q;
q.push(root);
string ans;
while (!q.empty()) {
root = q.front();
q.pop();
if (!ans.empty()) ans += ',';
if (root) {
ans += to_string(root->val);
q.push(root->left);
q.push(root->right);
} else ans += '#';
}
return ans;
}
TreeNode* deserialize(string data) {
if (data.empty()) return NULL;
stringstream ss(data);
string val;
vector v;
while (getline(ss, val, ',')) v.push_back(val);
TreeNode *root = new TreeNode(stoi(v[0]));
queue q;
q.push(root);
int i = 1;
while (i < v.size()) {
TreeNode *node = q.front();
q.pop();
node->left = getNode(v, i);
node->right = getNode(v, i);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
return root;
}
};
```
[⬆ Back to top](#table-of-contents)
## 79. Pacific Atlantic Water Flow
View Code
```cpp
class Solution {
int dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}, M, N;
void dfs(vector> &A, int x, int y, vector> &m) {
if (m[x][y]) return;
m[x][y] = 1;
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || a >= M || b < 0 || b >= N || A[a][b] < A[x][y]) continue;
dfs(A, a, b, m);
}
}
public:
vector> pacificAtlantic(vector>& A) {
if (A.empty() || A[0].empty()) return {};
M = A.size(), N = A[0].size();
vector> a(M, vector(N)), b(M, vector(N)), ans;
for (int i = 0; i < M; ++i) {
dfs(A, i, 0, a);
dfs(A, i, N - 1, b);
}
for (int j = 0; j < N; ++j) {
dfs(A, 0, j, a);
dfs(A, M - 1, j, b);
}
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (a[i][j] && b[i][j]) ans.push_back({i, j});
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 80. Delete and Earn
View Code
```cpp
int deleteAndEarn(vector& nums) {
vector dp(10002, 0);
vector sum(10002, 0);
for(auto a : nums) {
sum[a] += a;
}
dp[0] = sum[0];
dp[1] = sum[1];
for(int i = 2; i < 10001; i++) {
dp[i] = max(dp[i - 1], dp[i - 2] + sum[i]);
}
return dp[10000];
}
```
[⬆ Back to top](#table-of-contents)
## 81. Permutations II
View Code
```cpp
class Solution {
public:
vector> ans;
void permute(vector nums, int start) {
if(start == nums.size() - 1) {
ans.push_back(nums);
return;
}
for(int i = start; i < nums.size(); i++) {
if(i != start && nums[i] == nums[start]) continue;
swap(nums[i], nums[start]);
permute(nums, start + 1);
}
}
vector> permuteUnique(vector& nums) {
sort(nums.begin(), nums.end());
permute(nums, 0);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 82. Combination Sum II
View Code
```cpp
class Solution {
public:
vector> combinationSum2(vector& A, int target) {
int N = A.size();
sort(A.begin(), A.end());
vector> ans;
vector temp;
function dfs = [&](int start, int goal) {
if(goal == 0) {
ans.push_back(temp);
return;
}
for(int i = start; i < N && goal - A[i] >= 0 ; i++) {
if(i != start && A[i] == A[i - 1]) continue;
temp.push_back(A[i]);
dfs(i + 1, goal - A[i]);
temp.pop_back();
}
};
dfs(0, target);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 83. Non Overlapping Intervals
View Code
```cpp
int eraseOverlapIntervals(vector>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) {
return a[1] < b[1];
});
int overlapCnt = 0;
int end = INT_MIN;
for(auto &e : intervals) {
if(e[0] >= end) {
end = e[1];
} else {
overlapCnt++;
}
}
return overlapCnt;
}
```
[⬆ Back to top](#table-of-contents)
## 84. Best Time To Buy and Sell Stocks With Cooldown
View Code
```cpp
class Solution {
public:
int maxProfit(vector& A) {
if (A.empty()) return 0;
int N = A.size(), buy = INT_MIN;
vector dp(N + 1, 0);
for (int i = 0; i < N; ++i) {
buy = max(buy, (i >= 1 ? dp[i - 1] : 0) - A[i]);
dp[i + 1] = max(dp[i], buy + A[i]);
}
return dp[N];
}
};
```
[⬆ Back to top](#table-of-contents)
## 85. Maximum XOR of Two Numbers In An Array
Approach
This algorithm's idea is:
to iteratively determine what would be each bit of the final result from left to right. And it narrows down the candidate group iteration by iteration. e.g. assume input are `a,b,c,d,...z`, `26` integers in total. In first iteration, if you found that `a, d, e, h, u` differs on the MSB(most significant bit), so you are sure your final result's MSB is set. Now in second iteration, you try to see if among `a, d, e, h, u` there are at least two numbers make the 2nd MSB differs, if yes, then definitely, the 2nd MSB will be set in the final result. And maybe at this point the candidate group shinks from `a,d,e,h,u` to `a, e, h`. Implicitly, every iteration, you are narrowing down the candidate group, but you don't need to track how the group is shrinking, you only cares about the final result.
* The mask will grow like `100..000 , 110..000, 111..000, then 1111...111` for each iteration, we only care about the left parts.
* We only care about the left parts, for example, if `i = 2`, then we have `{1100, 1000, 0100, 0000}` from `{1110, 1011, 0111, 0010}`.
* If `i = 1`and before this iteration, the maxResult we have now is `1100`, my wish is the maxResult will grow to `1110`, so I will try to find a candidate which can give me the greedyTry.
* This is the most tricky part, coming from a fact that if `a ^ b = c`, then `a ^ c = b`, now we have the `c`, which is greedyTry, and we have the `a`, which is leftPartOfNum. If we hope the formula `a ^ b = c` to be valid, then we need the `b`, and to get `b`, we need `a ^ c`, if `a ^ c` exisited in our set, then we're good to go.
Solution - Bitmasks
```cpp
class Solution {
public:
int findMaximumXOR(vector& A) {
unordered_set s;
int mask = 0, ans = 0;
for (int i = 31; i >= 0; --i) {
mask |= 1 << i;
s.clear();
for (int n : A) s.insert(n & mask);
int next = ans | (1 << i);
for (int prefix : s) {
if (!s.count(next ^ prefix)) continue;
ans |= 1 << i;
break;
}
}
return ans;
}
};
```
Solution - Trie
```cpp
struct TrieNode {
TrieNode *next[2] = {};
};
class Solution {
void add(TrieNode *node, int n) {
for (int i = 31; i >= 0; --i) {
int b = n >> i & 1;
if (node->next[b] == NULL) node->next[b] = new TrieNode();
node = node->next[b];
}
}
int maxXor(TrieNode *node, int n) {
int ans = 0;
for (int i = 31; i >= 0; --i) {
int b = n >> i & 1;
if (node->next[1 - b]) { // if we can go the opposite direction, do it.
node = node->next[1 - b];
ans |= 1 << i;
} else {
node = node->next[b];
}
}
return ans;
}
public:
int findMaximumXOR(vector& A) {
TrieNode root;
int ans = 0;
for (int n : A) {
add(&root, n);
ans = max(ans, maxXor(&root, n));
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 86. Implement Queue Using Stacks
View Code
```cpp
class MyQueue {
public:
stack S1, S2;
void push(int x) {
while(!S1.empty()) {
S2.push(S1.top());
S1.pop();
}
S2.push(x);
while(!S2.empty()) {
S1.push(S2.top());
S2.pop();
}
}
int pop() {
int x = S1.top();
S1.pop();
return x;
}
int peek() {
return S1.top();
}
bool empty() {
return S1.empty();
}
};
```
[⬆ Back to top](#table-of-contents)
## 87. Minimum Size Subarray Sum
View Code
```cpp
int minSubArrayLen(int target, vector& nums) {
int N = nums.size();
int i = 0, sum = 0, ans = INT_MAX;
for(int j = 0; j < N; j++) {
sum += nums[j];
while(sum >= target) {
if(sum >= target) {
ans = min(ans, j - i + 1);
}
sum -= nums[i++];
}
}
return ans == INT_MAX ? 0 : ans;
}
```
[⬆ Back to top](#table-of-contents)
## 88. Number of Visible People In A Queue
View Code
```cpp
vector canSeePersonsCount(vector& A) {
stack S;
int N = A.size();
vector ans(N, 0);
for(int i = 0; i < N; i++) {
// Monotonically Increasing Sequence
while(S.size() && A[S.top()] <= A[i]) {
ans[S.top()]++;
S.pop();
}
if(S.size()) {
ans[S.top()]++;
}
S.push(i);
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 89. Describe The Painting
View Code
```cpp
class Solution {
public:
vector> splitPainting(vector>& segments) {
long long line[200001] = {};
bool change[200001] = {};
int maxEnd = -1;
for(auto &e : segments) {
int start = e[0], end = e[1], value = e[2];
line[start] += value;
line[end] -= value;
change[start] = change[end] = true;
maxEnd = max(maxEnd, end);
}
for(int i = 1; i <= maxEnd; i++) {
line[i] += line[i - 1];
}
vector> ans;
for(int i = 0; i <= maxEnd;) {
int start = i;
while(i <= maxEnd && line[i] == line[start] && (i == start || !change[i])) i++;
if(line[start]) {
ans.push_back({start, i, line[start]});
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 90. Flood Fill
View Code
```cpp
class Solution {
public:
int dirs[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int M, N, startingColor;
void dfs(vector> &image, int x, int y, int C) {
image[x][y] = C;
for(auto &dir : dirs) {
int a = x + dir[0];
int b = y + dir[1];
if(a < 0 || b < 0 || a >= M || b >= N || image[a][b] != startingColor) continue;
dfs(image, a, b, C);
}
}
vector> floodFill(vector>& image, int sr, int sc, int color) {
M = image.size();
N = image[0].size();
startingColor = image[sr][sc];
if(color == startingColor) {
return image;
}
dfs(image, sr, sc, color);
return image;
}
};
```
[⬆ Back to top](#table-of-contents)
## 91. Palindrome Partitioning
View Code
```cpp
class Solution {
public:
bool isPalindrome(string &s, int i, int j) {
while(i < j && s[i] == s[j]) {
i++;
j--;
}
return i >= j;
}
vector> ans;
vector temp;
void dfs(string &s, int start) {
if(start == s.size()) {
ans.push_back(temp);
return;
}
for(int i = start; i < s.length(); i++) {
if(!isPalindrome(s, start, i)) continue;
temp.push_back(s.substr(start, i - start + 1));
dfs(s, i + 1);
temp.pop_back();
}
}
vector> partition(string s) {
dfs(s, 0);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 92. Path With Maximum Gold
View Code
```cpp
class Solution {
public:
int M, N;
int dirs[4][2] = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int maxGold = 0;
void dfs(vector>& grid, int x, int y, int cnt) {
// Store gold in current cell.
int gold = grid[x][y];
grid[x][y] = 0;
cnt += gold;
maxGold = max(maxGold, cnt);
for(auto &dir : dirs) {
int a = x + dir[0];
int b = y + dir[1];
if(a < 0 || b < 0 || a >= M || b >= N || grid[a][b] == 0) continue;
dfs(grid, a, b, cnt);
}
grid[x][y] = gold;
}
int getMaximumGold(vector>& grid) {
M = grid.size();
N = grid[0].size();
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(grid[i][j] == 0) continue;
dfs(grid, i, j, 0);
}
}
return maxGold;
}
};
```
[⬆ Back to top](#table-of-contents)
## 93. Counting Bits
View Code
```cpp
class Solution {
public:
vector countBits(int N) {
vector dp(N + 1);
dp[0] = 0;
for(int i = 1; i <= N; i++) {
dp[i] = dp[i / 2] + (i & 1);
}
return dp;
}
};
```
[⬆ Back to top](#table-of-contents)
## 94. Word Break
View Code
```cpp
class Solution {
public:
bool wordBreak(string s, vector& wordDict) {
unordered_set M(wordDict.begin(), wordDict.end());
int N = s.size();
vector dp(N + 1);
dp[0] = true;
for(int i = 1; i <= N; i++) {
for(int j = 0; j < i && !dp[i]; j++) {
dp[i] = dp[j] && M.count(s.substr(j, i - j));
}
}
return dp[N];
}
};
```
[⬆ Back to top](#table-of-contents)
## 95. Find Median From Data Stream
View Code
```cpp
class MedianFinder {
public:
priority_queue, greater> maxHeap;
priority_queue> minHeap;
void addNum(int num) {
if(minHeap.empty()) {
minHeap.push(num);
} else if(num < minHeap.top()) {
maxHeap.push(minHeap.top());
minHeap.pop();
minHeap.push(num);
} else {
maxHeap.push(num);
}
while(maxHeap.size() > minHeap.size()) {
minHeap.push(maxHeap.top());
maxHeap.pop();
}
}
double findMedian() {
if(maxHeap.size() == minHeap.size()) {
return (double)(maxHeap.top() + minHeap.top()) / 2;
} else {
return (double)(minHeap.top());
}
}
};
```
[⬆ Back to top](#table-of-contents)
## 96. Single Threaded CPU
View Code
```cpp
class Solution {
typedef pair T;
public:
vector getOrder(vector>& A) {
priority_queue, greater<>> pq;
long N = A.size(), time = 0, i = 0;
for (int i = 0; i < N; ++i) A[i].push_back(i);
sort(begin(A), end(A));
vector ans;
while (i < N || pq.size()) {
if (pq.empty()) {
time = max(time, (long)A[i][0]);
}
while (i < N && time >= A[i][0]) {
pq.emplace(A[i][1], A[i][2]);
++i;
}
auto [pro, index] = pq.top();
pq.pop();
time += pro;
ans.push_back(index);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 97. Contiguous Array
View Code
```cpp
int findMaxLength(vector& A) {
unordered_map m{{0,-1}};
int ans = 0;
for (int i = 0, sum = 0; i < A.size(); ++i) {
sum += A[i] ? 1 : -1;
if (m.count(sum)) ans = max(ans, i - m[sum]);
else m[sum] = i;
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 98. Falling Squares
View Code
```cpp
class Solution {
public:
int n;
vector height, lazy;
void push_up(int i) {
height[i] = max(height[i*2], height[i*2+1]);
}
void push_down(int i) {
if (lazy[i]) {
lazy[i*2] = lazy[i*2+1] = lazy[i];
height[i*2] = height[i*2+1] = lazy[i];
lazy[i] = 0;
}
}
void update(int i, int l, int r, int L, int R, int val) {
if (L <= l && r <= R) {
height[i] = val;
lazy[i] = val;
return;
}
push_down(i);
int mid = l + (r-l)/2;
if (L < mid) update(i*2, l, mid, L, R, val);
if (R > mid) update(i*2+1, mid, r, L, R, val);
push_up(i);
}
int query(int i, int l, int r, int L, int R) {
if (L <= l && r <= R) return height[i];
push_down(i);
int res = 0;;
int mid = l + (r-l)/2;
if (L < mid) res = max(res, query(i*2, l, mid, L, R));
if (R > mid) res = max(res, query(i*2+1, mid, r, L, R));
return res;
}
vector fallingSquares(vector>& positions) {
vector a;
for (auto& p : positions) {
a.push_back(p.first);
a.push_back(p.first+p.second);
}
sort(a.begin(), a.end());
n = unique(a.begin(), a.end()) - a.begin();
a.resize(n);
height.resize(n<<2, 0);
lazy.resize(n<<2, 0);
vector res;
for (auto& p : positions) {
int l = lower_bound(a.begin(), a.end(), p.first) - a.begin();
int r = lower_bound(a.begin(), a.end(), p.first+p.second) - a.begin();
int maxh = query(1, 0, n, l, r);
update(1, 0, n, l, r, maxh+p.second);
res.push_back(query(1, 0, n, 0, n));
}
return res;
}
};
```
[⬆ Back to top](#table-of-contents)
## 99. Minimum XOR Sum of Two Arrays
View Code
```cpp
class Solution {
int dp[15][17000];
int recursion(vector &nums1, vector&nums2, int i, int mask) {
if(i >= nums1.size()) return 0;
if(dp[i][mask] != -1) return dp[i][mask];
int ans = INT_MAX;
for(int j = 0; j < nums2.size(); j++) {
if(mask & (1 << j)) continue;
int val = nums1[i] ^ nums2[j];
ans = min(ans, recursion(nums1, nums2, i + 1, mask | (1 << j)) + val);
}
return dp[i][mask] = ans;
}
public:
int minimumXORSum(vector& nums1, vector& nums2) {
memset(dp, -1, sizeof(dp));
return recursion(nums1, nums2, 0, 0);
}
};
```
[⬆ Back to top](#table-of-contents)
## 100. Maximum Profit In Job Scheduling
View Code
```cpp
class Solution {
public:
int jobScheduling(vector& startTime, vector& endTime, vector& profit) {
vector> jobs;
for (int i = 0; i < startTime.size(); ++i) jobs.push_back({ startTime[i], endTime[i], profit[i] });
sort(begin(jobs), end(jobs), greater<>());
map dp{{INT_MAX, 0}};
int ans = 0;
for (auto &[s, e, p] : jobs) {
dp[s] = max(ans, p + dp.lower_bound(e)->second);
ans = max(ans, dp[s]);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 101. Find Minimum Time To Finish All Jobs
View Code
```cpp
int dp[13][1 << 12], sum[1 << 12];
class Solution {
public:
int minimumTimeRequired(vector& A, int k) {
int N = A.size();
memset(dp, 0x3f, sizeof(dp));
memset(sum, 0, sizeof(sum));
for (int i = 0; i <= k; ++i) dp[i][0] = 0;
for (int mask = 0; mask < (1 << N); ++mask) {
for (int i = 0; i < N; ++i) {
if (mask & (1 << i)) sum[mask] += A[i];
}
}
for (int i = 0; i < k; ++i) {
for (int mask = 0; mask < (1 << N); ++mask) {
for (int sub = mask; sub; sub = (sub - 1) & mask) {
dp[i + 1][mask] = min(dp[i + 1][mask], max(dp[i][mask ^ sub], sum[sub]));
}
}
}
return dp[k][(1 << N) - 1];
}
};
```
[⬆ Back to top](#table-of-contents)
## 102. Course Schedule
View Code
```cpp
bool canFinish(int n, vector>& E) {
vector> G(n);
vector indegree(n);
for (auto &e : E) {
G[e[1]].push_back(e[0]);
++indegree[e[0]];
}
queue q;
for (int i = 0; i < n; ++i) {
if (indegree[i] == 0) q.push(i);
}
while (q.size()) {
int u = q.front();
q.pop();
--n;
for (int v : G[u]) {
if (--indegree[v] == 0) q.push(v);
}
}
return n == 0;
}
```
[⬆ Back to top](#table-of-contents)
## 103. Minimum Height Trees
View Code
```cpp
vector findMinHeightTrees(int n, vector>& E) {
if (n == 1) return { 0 };
vector degree(n), ans;
vector> G(n);
for (auto &e : E) {
int u = e[0], v = e[1];
degree[u]++;
degree[v]++;
G[u].push_back(v);
G[v].push_back(u);
}
queue q;
for (int i = 0; i < n; ++i) {
if (degree[i] == 1) q.push(i);
}
while (n > 2) {
int cnt = q.size();
n -= cnt;
while (cnt--) {
int u = q.front();
q.pop();
for (int v : G[u]) {
if (--degree[v] == 1) q.push(v);
}
}
}
while (q.size()) {
ans.push_back(q.front());
q.pop();
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 104. Russian Doll Envelopes
View Code
```cpp
int maxEnvelopes(vector>& A) {
sort(begin(A), end(A), [](auto &a, auto &b) { return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1]; });
vector dp;
for (auto &v : A) {
auto it = lower_bound(begin(dp), end(dp), v[1]);
if (it == end(dp)) dp.push_back(v[1]);
else *it = v[1];
}
return dp.size();
}
```
[⬆ Back to top](#table-of-contents)
## 105. Maximum AND Sum of Array
View Code
```cpp
int maximumANDSum(vector& A, int numSlots) {
A.resize(2 * numSlots); // append 0s to make sure the length of `A` is `2 * numSlots`
int N = A.size();
vector dp(1 << N);
for (int m = 1; m < 1 << N; ++m) {
int cnt = __builtin_popcount(m), slot = (cnt + 1) / 2;
for (int i = 0; i < N; ++i) {
if (m >> i & 1) { // we assign A[i] to `slot`-th slot
dp[m] = max(dp[m], dp[m ^ (1 << i)] + (slot & A[i]));
}
}
}
return dp[(1 << N) - 1];
}
```
[⬆ Back to top](#table-of-contents)
## 106. Maximum Number of Robots Within Budget
View Code - Sliding Window
```cpp
int maximumRobots(vector& times, vector& costs, long long budget) {
long long N = times.size(), ans = 0, i = 0, sum = 0;
multiset S;
for(int j = 0; j < N; j++) {
sum += costs[j];
S.insert(times[j]);
// *S.rbegin() will return the largest element present in multiset.
if(*S.rbegin() + (sum * (j - i + 1)) > budget) {
sum -= costs[i];
S.erase(S.find(times[i++]));
}
}
return N - i;
}
```
`Why does returning N - i works ?`
That's really the ingenious part of this implementation. The key is in the `if` statement. We are not using `while` loop which is what people typically do. By using `if`, it is guaranteed that the distance between i and j will not decrease once it reaches certain value. As a result, `N - i` will be the largest value one has seen in the loop.
View Code - Sparse Table and Binary Search
```cpp
#define ll long long
struct sparse_table {
ll level, n;
vector> table;
vector lg;
sparse_table(vector &a) {
n = a.size();
level = ceil(log2(n));
table.resize(n, vector (level + 1));
lg.resize(n + 1);
build(a);
}
void build(vector &a) {
lg[1] = 0;
for(int i = 2; i < n + 1; ++i)
lg[i] = lg[i / 2] + 1;
for(int i = 0; i < n; ++i)
table[i][0] = a[i];
for(int j = 1; j <= level; ++j) {
for(int i = 0; i + (1LL << j) <= n; ++i) {
table[i][j] = max(table[i][j - 1], table[i + (1LL << (j - 1))][j - 1]);
}
}
}
ll query(ll l, ll r) {
l--, r--;
ll j = lg[r - l + 1];
return max(table[l][j], table[r - (1LL << j) + 1][j]);
}
};
class Solution {
public:
int maximumRobots(vector& ct, vector& rt, long long budget) {
ll n = ct.size();
sparse_table rmq(ct); // for getting maximum in a range [l, r] in O(1)
vector pre(n + 1, 0);
for(int i = 0; i < n; ++i) pre[i + 1] = pre[i] + rt[i]; // precalculating prefix sums on running costs
ll res = 0;
for(int i = 0; i < n; ++i) {
int lo = i, hi = n - 1, ind = -1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
ll mx = rmq.query(i + 1, mid + 1); // maximum in the current range
ll sum = pre[mid + 1] - pre[i]; // range sum
if(mx + (mid - i + 1) * sum <= budget) { // if the current range cost is less than or equal to budget
ind = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if(ind != -1) {
res = max(res, 1LL * (ind - i + 1));
}
}
return res;
}
};
```
[⬆ Back to top](#table-of-contents)
## 107. Find Longest Awesome Substring
Approach
Encode the parity of each digit using bit mask. For example, if we've seen `001233444`, we encode it as `10110` because there are odd numbers of `1, 2, 4` and even numbers of `0, 3`.
We use a map `m` to store the mapping from the bitmask to the index of the first occurrence of that bitmask.
For the current `mask`, we have two options:
* all the digits in the window appeared even number times. The maximum length of such window is `i - m[mask]`.
* Only a single digit in the window appeared odd number times. Assume it's digit `0 <= j < 9`, the maximum length of such window is `i - m[mask ^ (1 << j)]`
For example - consider this number - `3242415`
* Mask at i = 0 is `00001000`
* Mask at i = 1 is `00001100`
* Mask at i = 2 is `00011100`
* Mask at i = 3 is `00011000`
* Mask at i = 4 is `00001000`
* Mask at i = 5 is `00001010`
* Mask at i = 6 is `00101010`
In this case, if you see the mask at index `i = 0` and `i = 4` are same, hence we will store it in answer as `4 - 0 + 1` as `5`.
For checking single digits if it is appeared odd number of times.
In our case, mask at `i = 0` is `0000001000`
We will try to check if any of the digits is odd from 0 to 9, by doing `mask ^ (1 << j)`
Mask at `j = 0` is `0000001001`
Mask at `j = 1` is `0000001010`
Mask at `j = 2` is `0000001100`
Mask at `j = 3` is `0000000000`
Mask at `j = 4` is `0000011000`
Mask at `j = 5` is `0000101000`
Mask at `j = 6` is `0001001000`
Mask at `j = 7` is `0010001000`
Mask at `j = 8` is `0100001000`
Mask at `j = 9` is `1000001000`
Solution - Bitmasks and Prefix State Map
```cpp
class Solution {
public:
int longestAwesome(string s) {
unordered_map m{{0,-1}}; // mask -> index of first occurrence
int ans = 0;
for (int i = 0, mask = 0; i < s.size(); ++i) {
mask ^= 1 << (s[i] - '0');
if (m.count(mask)) ans = max(ans, i - m[mask]);
else m[mask] = i;
for (int j = 0; j < 10; ++j) {
int prev = mask ^ (1 << j);
if (m.count(prev)) ans = max(ans, i - m[prev]);
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 108. Maximum Rows Covered By Columns
Solution - Bitmasks
```cpp
int maximumRows(vector>& a, int cols) {
int n = (int) a.size();
int m = (int) a[0].size();
int ans = -1;
for (int mask = 0; mask < (1 << m); mask++) {
if (__builtin_popcount(mask) != cols) {
continue;
}
int t = (1 << n) - 1;
for (int i = 0; i < m; i++) {
if (~mask & (1 << i)) {
for (int j = 0; j < n; j++) {
if (a[j][i]) {
t &= ~(1 << j);
}
}
}
}
ans = max(ans, __builtin_popcount(t));
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 109. Create Sorted Array Through Instructions
Solution - Binary Indexed Tree (Fenwick Tree)
```cpp
int c[100001];
int createSortedArray(vector& A) {
memset(c, 0, sizeof(c));
int res = 0, n = A.size(), mod = 1e9 + 7;
for (int i = 0; i < n; ++i) {
res = (res + min(get(A[i] - 1), i - get(A[i]))) % mod;
update(A[i]);
}
return res;
}
void update(int x) {
while (x < 100001) {
c[x]++;
x += x & -x;
}
}
int get(int x) {
int res = 0;
while (x > 0) {
res += c[x];
x -= x & -x;
}
return res;
}
```
Solution - Segment Tree
```cpp
// Segment Tree Array
int tree[400040];
int get_mid(int a, int b) {
return a + (b - a)/2;
}
// Fn to get sum between range s to e
int query(int index, int s, int e, int qs, int qe) {
// 1. Base Case - Complete Overlapp
if(s >= qs and e <= qe)
return tree[index];
// 2. Base Case - No overlapp
if(e < qs or s > qe)
return 0;
// 3. Partial Overlapp
int mid = get_mid(s, e);
int leftAns = query(2*index + 1, s, mid, qs, qe);
int rightAns = query(2*index + 2, mid + 1, e, qs, qe);
return leftAns + rightAns;
}
void update(int index, int s, int e, int pos) {
// 1. Base Case - Reached the node where update is required
if(s == e) {
tree[index]++;
return;
}
// 2. Intermidiate Node
int mid = get_mid(s, e);
if(pos <= mid)
update(2*index + 1, s, mid, pos);
else
update(2*index + 2, mid + 1, e, pos);
tree[index] = tree[2*index + 1] + tree[2*index + 2];
}
int createSortedArray(vector& instructions) {
int cost = 0;
const int MAXN = 1e5 + 1;
const int MOD = 1e9 + 7;
for(auto x : instructions) {
// Get number of elements that are less than current element
int less_count = query(0, 0, MAXN, 0, x - 1);
// Get number of elements which are greater than current element
int greater_count = query(0, 0, MAXN, x + 1, MAXN);
update(0, 0, MAXN, x);
cost = (cost + min(less_count, greater_count))%MOD;
}
return cost;
}
```
[⬆ Back to top](#table-of-contents)
## 110. Maximum Students Taking Exam
Approach
We can do the dp row by row, we start from row 1 until row n.
`dp[i][mask]` represents that, we are now at row i and the state of this row is mask.
Now, state conversion is: We consider every possible state of the last row, and check if the state conversion is legal (that is, there will be no cheating). Hence we have:
`dp[i][mask] = max(dp[i][mask], dp[i-1][premask] + __builtin_popcount(mask));`
where mask and premask are both legal, and these two rows together will have no cheating.
Solution - Bitmasks
```cpp
class Solution {
public:
int n,m;
int ans = 0;
int dp[9][(1<<8)+2]; //dp[i][mask]: we are in row i(i is from [1,9]), state is mask
int avail[9]; //avail[i] is the mask representing available seats in row i
int maxStudents(vector>& seats) {
n = seats.size(); m = seats[0].size();
memset(dp, -1, sizeof(dp));
for (int i = 1; i <= n; i++) {
for (int j = 0; j < m; j++) {
if (seats[i-1][j] == '.') {
avail[i] |= (1<>1)) continue; //if there is adjacent 1
/*checking this row and last row*/
if (mask&(premask<<1) || mask&(premask>>1)) continue;
dp[i][mask] = max(dp[i][mask], dp[i-1][premask] + __builtin_popcount(mask));
}
}
}
for (int mask = 0; mask < (1<
[⬆ Back to top](#table-of-contents)
## 111. Number of Ways To Reach A Position After Exactly K Steps
Solution - Recursion + DP
```cpp
class Solution {
public:
vector> dp;
const int MOD = 1e9 + 7;
int recur(int s, int e, int step, int current, int k) {
if(dp[step][current + 2000] != -1e9) {
return (dp[step][current + 2000] % MOD);
}
if(step == k) {
if(current == e) {
return 1;
}
return 0;
}
return dp[step][current + 2000] = ((recur(s, e, step + 1, current + 1, k) % MOD) + (recur(s, e, step + 1, current - 1, k) % MOD)) % MOD;
}
int numberOfWays(int startPos, int endPos, int k) {
dp.assign(5000, vector(5000, -1e9));
return recur(startPos, endPos, 0, startPos, k) % MOD;
}
};
```
[⬆ Back to top](#table-of-contents)
## 112. Find The Longest Substring Containing Vowels In Even Counts
Approach
At the first glance it's like a sliding window problem. For a find maximum sliding window problem, the initial state should be valid, then keep extending the 2nd pointer until the state becomes invalid (now the maximum is found), then move the first pointer to get back the valid state again.
In this problem, the initial state is valid. When extending the 2nd pointer, the state might jump back and forth between invalid and valid before reaching the longest valid end position. So we shouldn't use sliding window to solve this problem.
Try to get the intuition by simplying the problem -- what if we only consider `a` as vowel?
```
4 9 13 17
v v v v
xxxxaxxxxaxxxaxxxaxxx
~
-1
4
-1
```
Consider the above input.
For `i = 0 ~ 3`, `0` `a` has been visited, substring `s[0..i]` is valid.
For `i = 4 ~ 8`, `1` `a` has been visited, substring `s[5..i]` is valid.
For `i = 9 ~ 12`, `2` `a`s have been visited, substring `s[0..i]` is valid.
For `i = 13 ~ 16`, `3` `a`s have been visited, substring `s[5..i]` is valid.
For `i = 17 ~ (N - 1)`, `4` `a`s have been visited, substring `s[0..i]` is valid.
So we can see there can be a greedy solution:
* If we've visited **even** number of `a`, substring `s[0..i]` is valid which has length `i + 1`.
* If we've visited **odd** number of `a`, substring `s[(k+1)..i]` is valid where `k` is the first index of the first occurrence of `a`. The length is `i - k`.
We can regard **even** and **odd** are two different states, then the above two cases can be unified into one:
* If we are in state `x` at index `i`, find the index of the first occurrence of the same state `x`, say `k`, then `i - k` is the length of the longest valid string ending at `i`.
Note that we need to regard `-1` as the index of the first occurrence of **even** state.
Now we consider the 5 vowels. Each vowel has two different states, **even** and **odd**. So in total there are `2^5` different states. We can use bitmask to encode the state.
For example, if the state of `aeiou` are even, even, odd, odd, even respectively, we can encode the state as `00110`.
Let `index` be a map from state `x` to the index of the first occurrence of state `x`.
For each index `i`, we get the corresponding state `mask` of `s[i]` first, then:
* If we've seen this state, then try to update the answer using `i - index[mask]`.
* Otherwise, `index[mask] = i`.
Solution - Prefix State Map
```cpp
int findTheLongestSubstring(string s) {
int h = 0, ans = 0;
unordered_map m{{'a',0},{'e',1},{'i',2},{'o',3},{'u',4}}, index{{0,-1}};
for (int i = 0; i < s.size(); ++i) {
if (m.count(s[i])) h ^= 1 << m[s[i]];
if (index.count(h)) ans = max(ans, i - index[h]);
else index[h] = i;
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 113. Maximum Earnings From Taxi
Solution
```cpp
long long maxTaxiEarnings(int n, vector>& A) {
sort(A.begin(), A.end(), [](auto &a, auto &b) { return a[0] > b[0]; });
map dp;
dp[INT_MAX] = 0;
long long ans = 0;
for(auto &r : A) {
int s = r[0], e = r[1], p = r[2];
dp[s] = max(ans, e - s + p + dp.lower_bound(e)->second);
ans = max(ans, dp[s]);
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 114. Vertical Order Traversal Of A Binary Tree
Solution
```cpp
class Solution {
public:
vector> answer;
map>> m;
void dfs(TreeNode* root, int x, int y) {
if(!root) {
return;
}
m[x][y].insert(root->val);
dfs(root->left, x - 1, y + 1);
dfs(root->right, x + 1, y + 1);
}
vector> verticalTraversal(TreeNode* root) {
dfs(root, 0, 0);
for(auto &[mm, mm1]: m) {
answer.emplace_back();
for(auto &[mm2, vals] : mm1) {
for(int n : vals) {
answer.back().push_back(n);
}
}
}
return answer;
}
};
```
[⬆ Back to top](#table-of-contents)
## 115. Invert Binary Tree
Solution
```cpp
TreeNode* invertTree(TreeNode* root) {
if(!root) {
return NULL;
}
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
```
[⬆ Back to top](#table-of-contents)
## 116. Count Primes
Solution
```cpp
int countPrimes(int n) {
vector primes(n + 1, true);
int cntPrimes = 0;
for(int i = 2; i < n; i++) {
if(!primes[i]) {
continue;
}
cntPrimes++;
for(int j = i; j < n; j += i) {
primes[j] = false;
}
}
return cntPrimes;
}
```
[⬆ Back to top](#table-of-contents)
## 117. Find The Shortest Superstring
Solution
```cpp
class Solution {
public:
string shortestSuperstring(vector& A) {
int n = A.size();
vector> overlaps(n, vector(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int m = min(A[i].size(), A[j].size());
for (int k = m; k >= 0; --k) {
if (A[i].substr(A[i].size() - k) == A[j].substr(0, k)) {
overlaps[i][j] = k;
break;
}
}
}
}
// dp[mask][i] = most overlap with mask, ending with ith element
vector> dp(1<(n, 0));
vector> parent(1<(n, -1));
for (int mask = 0; mask < (1<>bit)&1) > 0) {
int pmask = mask^(1<>i)&1) > 0) {
int val = dp[pmask][i] + overlaps[i][bit];
if (val > dp[mask][bit]) {
dp[mask][bit] = val;
parent[mask][bit] = i;
}
}
}
}
}
}
vector perm;
vector seen(n);
int mask = (1< dp[(1<
[⬆ Back to top](#table-of-contents)
## 118. Sum Root To Leaf Nodes
Solution
```cpp
class Solution {
public:
int ans = 0;
void dfs(TreeNode* root, int sum) {
if(!root) return;
sum = sum * 10 + (root->val);
if(!root->left && !root->right) ans += sum;
dfs(root->left, sum);
dfs(root->right, sum);
}
int sumNumbers(TreeNode* root) {
dfs(root, 0);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 119. Longest Common Subsequence
Solution
```cpp
int longestCommonSubsequence(string s, string t) {
int M = s.size(), N = t.size();
vector> dp(M + 1, vector(N + 1, 0));
for(int i = 1; i <= M; i++) {
for(int j = 1; j <= N; j++) {
if (s[i - 1] == t[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[M][N];
}
```
[⬆ Back to top](#table-of-contents)
## 120. Count Number of Maximum Bitwise Or Subsets
Solution
```cpp
int countMaxOrSubsets(vector& nums) {
int N = nums.size(), maxOr = 0;
for(auto a : nums) maxOr |= a;
int subsetCnt = 0;
for(int mask = 0; mask < (1 << N); mask++) {
int subsetOr = 0;
for(int i = 0; i < N; i++) {
if(mask >> i & 1) {
subsetOr |= (nums[i]);
}
}
if(subsetOr == maxOr) subsetCnt++;
}
return subsetCnt++;
}
```
[⬆ Back to top](#table-of-contents)
## 121. Jump Game III
Solution - DP
```cpp
bool canReach(vector& A, int start) {
if(start < 0 || start >= A.size() || A[start] < 0) return false;
if(A[start] == 0) return true;
A[start] *= -1;
return canReach(A, start + A[start]) || canReach(A, start - A[start]);
}
```
[⬆ Back to top](#table-of-contents)
## 122. Operations on Tree
Solution
```cpp
class LockingTree {
vector locked, parent;
vector> child;
int N;
bool upwardValid(int i) {
if (i == -1) return true;
if (locked[i]) return false;
return upwardValid(parent[i]);
}
bool downwardValid(int i) {
if (locked[i]) return true;
for (int ch : child[i]) {
if (downwardValid(ch)) return true;
}
return false;
}
void downwardUnlock(int i) {
locked[i] = 0;
for (int ch : child[i]) {
downwardUnlock(ch);
}
}
public:
LockingTree(vector& parent) : parent(parent) {
N = parent.size();
locked.assign(N, 0);
child.assign(N, vector());
for (int i = 1; i < N; ++i) {
child[parent[i]].push_back(i);
}
}
bool lock(int num, int user) {
if (locked[num] != 0) return false;
locked[num] = user;
return true;
}
bool unlock(int num, int user) {
if (locked[num] != user) return false;
locked[num] = 0;
return true;
}
bool upgrade(int num, int user) {
if (!upwardValid(num) || !downwardValid(num)) return false;
downwardUnlock(num);
locked[num] = user;
return true;
}
};
```
[⬆ Back to top](#table-of-contents)
## 123. Minimum Operations To Convert Number
Solution
```cpp
int minimumOperations(vector& nums, int start, int goal) {
queue q;
q.push(start);
bool seen[1001] = {};
int step = 0;
seen[start] = true;
while(q.size()) {
int cnt = q.size();
while(cnt--) {
int n = q.front();
q.pop();
for(auto a : nums) {
for(int next : {n + a, n - a, n ^ a}) {
if(next == goal) return step + 1;
if(next < 0 || next > 1000 || seen[next]) continue;
seen[next] = true;
q.push(next);
}
}
}
step++;
}
return -1;
}
```
[⬆ Back to top](#table-of-contents)
## 124. Egg Drop With 2 Eggs and N Floors
Solution
```cpp
int twoEggDrop(int n) {
vector dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= i; ++j) {
dp[i] = min(dp[i], 1 + max(j - 1, dp[i - j]));
}
}
return dp[n];
}
```
Math Solution
```cpp
int twoEggDrop(int n) {
return ceil((-1 + sqrt(1 + 8 * n)) / 2);
}
```
[⬆ Back to top](#table-of-contents)
## 125. Time Needed To Inform All Employees
Solution
```cpp
class Solution {
public:
int numOfMinutes(int n, int head, vector& manager, vector& time) {
queue> q;
q.push({head, time[head]});
unordered_map> G;
int N = manager.size();
for(int i = 0; i < N; i++) {
if(manager[i] == -1) continue;
G[manager[i]].push_back(i);
}
int ans = 0;
while (q.size()) {
int cnt = q.size();
while (cnt--) {
auto u = q.front();
q.pop();
ans = max(ans, u.second);
for(int v : G[u.first]) {
q.push({v, time[v] + u.second});
}
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 126. Time Based Key-Value Store
Solution
```cpp
class TimeMap {
public:
unordered_map>> M;
void set(string key, string value, int timestamp) {
M[key][timestamp] = value;
}
string get(string key, int timestamp) {
if(M.count(key) == 0) return "";
auto it = M[key].lower_bound(timestamp);
if(it == M[key].end()) {
return "";
} else {
return it->second;
}
}
};
```
[⬆ Back to top](#table-of-contents)
## 127. Shortest Bridge
Solution
```cpp
class Solution {
int M, N, dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
queue> qa, qb;
void dfs(vector> &A, int x, int y, int color) {
A[x][y] = color;
if (color == 2) qa.emplace(x, y);
else qb.emplace(x, y);
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || b < 0 || a >= M || b >= N || A[a][b] != 1) continue;
dfs(A, a, b, color);
}
}
void bfs(vector> &A, queue> &q, vector> &dist) {
int step = 1;
while (q.size()) {
int cnt = q.size();
while (cnt--) {
auto [x, y] = q.front();
q.pop();
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || b < 0 || a >= M || b >= N || A[a][b] != 0 || dist[a][b] != INT_MAX) continue;
dist[a][b] = step;
q.emplace(a, b);
}
}
++step;
}
}
public:
int shortestBridge(vector>& A) {
M = A.size(), N = A[0].size();
int color = 2, ans = INT_MAX;
vector> da(M, vector(N, INT_MAX)), db(M, vector(N, INT_MAX));
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] == 1) dfs(A, i, j, color++);
}
}
bfs(A, qa, da);
bfs(A, qb, db);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] == 0 && da[i][j] != INT_MAX && db[i][j] != INT_MAX) ans = min(ans, da[i][j] + db[i][j] - 1);
}
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 128. Flip String To Monotone Increasing
Solution
```cpp
class Solution {
public:
int minFlipsMonoIncr(string s) {
int rightZeros = 0, leftOnes = 0;
for (char c : s) rightZeros += c == '0';
int ans = rightZeros;
for (char c : s) { // we make the current character the last `0`
if (c == '1') leftOnes++;
else rightZeros--;
ans = min(ans, rightZeros + leftOnes);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 129. Longest Increasing Subsequence - II
Solution
```cpp
class Solution {
public:
vector seg;
//Segment tree to return maximum in a range
void upd(int ind, int val, int x, int lx, int rx) {
if(lx == rx) {
seg[x] = val;
return;
}
int mid = lx + (rx - lx) / 2;
if(ind <= mid)
upd(ind, val, 2 * x + 1, lx, mid);
else
upd(ind, val, 2 * x + 2, mid + 1, rx);
seg[x] = max(seg[2 * x + 1], seg[2 * x + 2]);
}
int query(int l, int r, int x, int lx, int rx) {
if(lx > r or rx < l) return 0;
if(lx >= l and rx <= r) return seg[x];
int mid = lx + (rx - lx) / 2;
return max(query(l, r, 2 * x + 1, lx, mid), query(l, r, 2 * x + 2, mid + 1, rx));
}
int lengthOfLIS(vector& nums, int k) {
int x = 1;
while(x <= 200000) x *= 2;
seg.resize(2 * x, 0);
int res = 1;
for(int i = 0; i < nums.size(); ++i) {
int left = max(1, nums[i] - k), right = nums[i] - 1;
int q = query(left, right, 0, 0, x - 1); // check for the element in the range of [nums[i] - k, nums[i] - 1] with the maximum value
res = max(res, q + 1);
upd(nums[i], q + 1, 0, 0, x - 1); //update current value
}
return res;
}
};
```
[⬆ Back to top](#table-of-contents)
## 130. Solving Questions With Brainpower
Solution
```cpp
long long mostPoints(vector>& A) {
int N = A.size();
vector dp(N + 2);
for (int i = 0; i < N; ++i) {
dp[i + 1] = max(dp[i + 1], dp[i]);
int next = min(i + A[i][1] + 2, N + 1);
dp[next] = max(dp[next], dp[i + 1] + A[i][0]);
}
return dp[N + 1];
}
```
[⬆ Back to top](#table-of-contents)
## 131. Detonate The Maximum Bombs
Solution
```cpp
class Solution {
public:
int maximumDetonation(vector>& A) {
int N = A.size();
vector> G(N);
auto cover = [&](int i, int j) {
return pow((long)A[i][0] - A[j][0], 2) + pow((long)A[i][1] - A[j][1], 2) <= pow((long)A[i][2], 2);
};
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
if (cover(i, j)) G[i].push_back(j);
if (cover(j, i)) G[j].push_back(i);
}
}
vector seen(N);
function dfs = [&](int u) {
seen[u] = true;
int ans = 1;
for (int v : G[u]) {
if (seen[v]) continue;
ans += dfs(v);
}
return ans;
};
int ans = 0;
for (int i = 0; i < N; ++i) {
seen.assign(N, false);
ans = max(ans, dfs(i));
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 132. Fair Distribution of Cookies
Solution
```cpp
class Solution {
public:
int distributeCookies(vector& A, int K) {
int N = A.size();
vector> dp(K + 1, vector(1 << N, INT_MAX));
vector sum(1 << N);
for (int m = 1; m < (1 << N); ++m) {
int s = 0;
for (int i = 0; i < N; ++i) {
if (m >> i & 1) s += A[i];
}
sum[m] = s;
dp[1][m] = s;
}
for (int k = 2; k <= K; ++k) {
for (int m = 1; m < (1 << N); ++m) {
for (int s = m; s; s = (s - 1) & m) {
dp[k][m] = min(dp[k][m], max(dp[k - 1][m - s], sum[s]));
}
}
}
return dp[K][(1 << N) - 1];
}
};
```
[⬆ Back to top](#table-of-contents)
## 133. Minimum Cost To Reach Destination In Time
Solution
```cpp
class Solution {
typedef array Node; // node, time, cost
public:
int minCost(int maxTime, vector>& E, vector& F) {
int N = F.size();
vector> G(N);
vector minTime(N, maxTime + 1);
for (auto &e : E) {
int u = e[0], v = e[1], t = e[2];
if (G[u].count(v)) { // For duplicated edges, we just need to keep track of the edge with smallest time.
G[u][v] = G[v][u] = min(G[u][v], t);
} else {
G[u][v] = G[v][u] = t;
}
}
auto cmp = [](auto &a, auto &b) { return a[2] > b[2]; }; // min-heap: Heap top is the node with the smallest cost to reach
priority_queue, decltype(cmp)> pq(cmp);
pq.push({0, 0, F[0]});
minTime[0] = 0;
while (pq.size()) {
auto [u, time, c] = pq.top();
pq.pop();
if (u == N - 1) return c;
for (auto &[v, t] : G[u]) {
int nt = time + t, nc = c + F[v];
if (nt < minTime[v]) {
minTime[v] = nt;
pq.push({v, nt, nc});
}
}
}
return -1;
}
};
```
[⬆ Back to top](#table-of-contents)
## 134. Longest Substring of One Repeating Character
Solution
```cpp
class sgtree{
public:
vector nums, left, right;
vector lc, rc;
int n;
sgtree(string &s){
n = s.size();
nums = vector(4*n+5, 0);
left = vector(4*n+5, -1);
right = vector(4*n+5, -1);
lc = vector(4*n+5, '*');
rc = vector(4*n+5, '*');
build(0, s, 0, n-1);
}
void build(int in, string &s,int l,int h){
if(l > h) return;
if(l == h){
lc[in] = rc[in] = s[l];
left[in] = l,right[in] = l; nums[in] = 1;
return;
}
int m = (l + h) / 2;
build(2*in+1,s,l,m);
build(2*in+2,s,m+1,h);
merge(in,l,m,h);
}
void merge(int in,int l,int m,int h){
int lt = in*2+1, rt = in*2+2, max_ = 0;
lc[in] = lc[lt]; rc[in] = rc[rt];
left[in] = left[lt];
right[in] = right[rt];
if(rc[lt]==lc[rt]){
if(left[lt]==m) left[in] = left[rt];
}
if(lc[rt]==rc[lt]){
if(right[rt]==m+1) right[in] = right[lt];
}
if(rc[lt]==lc[rt]) max_ = left[rt]-right[lt]+1;
max_ = max(max_,left[in]-l+1);
max_ = max(max_,h-right[in]+1);
nums[in] = max(max_,max(nums[lt],nums[rt]));
}
int update(int in,int l,int h,int j,char ch){
if(l>h) return 0;
if(l==h){
lc[in] = rc[in] = ch;
left[in] = l,right[in] = l; nums[in] = 1;
return 1;
}
int m = (l+h)/2;
if(j>=l && j<=m) update(2*in+1,l,m,j,ch);
else update(2*in+2,m+1,h,j,ch);
merge(in,l,m,h);
return nums[in];
}
};
class Solution {
public:
vector longestRepeating(string s, string q, vector& in) {
sgtree node(s);
vector re(q.size(),0);
for(int i = 0; i
[⬆ Back to top](#table-of-contents)
## 135. Predict The Winner
Recursion
```cpp
```
DP
```cpp
bool PredictTheWinner(vector& nums) {
int N = nums.size();
unordered_map> dp;
for (int i = 0; i < N; ++i) dp[i][1] = nums[i];
for (int len = 2; len <= N; ++len) {
for (int i = 0; i <= N - len; ++i) {
dp[i][len] = max(nums[i] - dp[i + 1][len - 1], nums[i + len - 1] - dp[i][len - 1]);
}
}
return dp[0][N] >= 0;
}
```
[⬆ Back to top](#table-of-contents)
## 136. Path With Minimum Effort
Solution
```cpp
class Solution {
public:
int M, N;
int dirs[4][2] = { {0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int minimumEffortPath(vector>& A) {
M = A.size(), N = A[0].size();
vector> minCost(M, vector(N, INT_MAX));
priority_queue, vector>, greater<>> pq;
pq.push({0, 0, 0});
minCost[0][0] = 0;
while (pq.size()) {
auto [e, x, y] = pq.top();
pq.pop();
if(e > minCost[x][y]) continue;
if(x == M - 1 && y == N - 1) return minCost[x][y];
for (auto &dir : dirs) {
int a = x + dir[0];
int b = y + dir[1];
if (a < 0 || b < 0 || a >= M || b >= N) continue;
int effort = max(e, abs(A[a][b] - A[x][y]));
if(effort >= minCost[a][b]) continue;
minCost[a][b] = effort;
pq.push({effort, a, b});
}
}
return -1;
}
};
```
[⬆ Back to top](#table-of-contents)
## 137. Cheapest Flights Within K Stops
Solution
```cpp
class Solution {
public:
typedef array Item; // Cost, CityID, Stops Left
int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) {
// Creation of Adjacent List
vector>> G(n);
for(auto &e : flights) {
int u = e[0], v = e[1], w = e[2];
G[u].push_back({v, w});
}
k++;
priority_queue- , greater<>> pq;
pq.push({0, src, k});
vector> dist(k + 1, vector(n, INT_MAX));
for(int i = 0; i <= k; i++) {
dist[i][src] = 0;
}
while (pq.size()) {
auto [c, u, stop] = pq.top();
pq.pop();
if (c > dist[stop][u]) continue;
if (u == dst) return c;
if (stop == 0) continue;
for (auto &[v, w] : G[u]) {
if (dist[stop - 1][v] > c + w) {
dist[stop - 1][v] = c + w;
pq.push({dist[stop - 1][v], v, stop - 1});
}
}
}
return -1;
}
};
```
[⬆ Back to top](#table-of-contents)
## 138. Minimum Cost To Make at Least One Valid Path in Grid
Solution
```cpp
class Solution {
public:
int dirs[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int minCost(vector>& grid) {
int M = grid.size();
int N = grid[0].size();
int dist[100][100] = {};
memset(dist, 0x3f, sizeof(dist));
priority_queue, vector>, greater<>> pq;
pq.push({ 0, 0, 0 });
dist[0][0] = 0;
while (pq.size()) {
auto [cost, x, y] = pq.top();
pq.pop();
if (cost > dist[x][y]) continue;
if (x == M - 1 && y == N - 1) return cost;
for (int i = 0; i < 4; i++) {
int a = x + dirs[i][0];
int b = y + dirs[i][1];
int newCost = cost + (grid[x][y] - 1 != i);
if (a < 0 || b < 0 || a >= M || b >= N) continue;
if (dist[a][b] > newCost) {
dist[a][b] = newCost;
pq.push({ newCost, a, b});
}
}
}
return 0;
}
};
```
[⬆ Back to top](#table-of-contents)
## 139. Frog Jump
Solution
```cpp
class Solution {
vector> memo;
private:
bool dfs(vector &A, int i, int k) {
if (i == A.size() - 1) return true;
if (memo[i].count(k)) return false;
int j = i + 1;
for (int d = -1; d <= 1; ++d) {
int move = k + d;
if (move <= 0) continue;
while (j < A.size() && A[j] - A[i] < move) ++j;
if (j >= A.size()) return false;
if (A[j] - A[i] == move && dfs(A, j, move)) return true;
}
memo[i].insert(k);
return false;
}
public:
bool canCross(vector& A) {
memo.assign(A.size(), {});
return dfs(A, 0, 0);
}
};
```
[⬆ Back to top](#table-of-contents)
## 140. Find Eventual Safe State
Solution
```cpp
vector eventualSafeNodes(vector>& G) {
int N = G.size();
vector> R(N);
vector outdegree(N), safe(N), ans;
queue q;
for (int i = 0; i < N; ++i) {
for (int v : G[i]) {
R[v].push_back(i);
}
outdegree[i] = G[i].size();
if (outdegree[i] == 0) q.push(i);
}
while (q.size()) {
int u = q.front();
q.pop();
safe[u] = 1;
for (int v : R[u]) {
if (--outdegree[v] == 0) q.push(v);
}
}
for (int i = 0; i < N; ++i) {
if (safe[i]) ans.push_back(i);
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 141. No of Ways To Arrive At Destination
Solution
```cpp
class Solution {
typedef pair ipair;
public:
int countPaths(int n, vector>& E) {
vector>> G(n);
for (auto &e : E) {
int u = e[0], v = e[1], t = e[2];
G[u].emplace_back(v, t);
G[v].emplace_back(u, t);
}
long mod = 1e9 + 7;
vector dist(n, LONG_MAX), cnt(n);
priority_queue, greater<>> pq; // time, city
dist[0] = 0;
cnt[0] = 1;
pq.emplace(0, 0);
while (pq.size()) {
auto [cost, u] = pq.top();
pq.pop();
if (cost > dist[u]) continue;
for (auto &[v, time] : G[u]) {
long c = cost + time;
if (c < dist[v]) {
dist[v] = c;
cnt[v] = cnt[u];
pq.emplace(c, v);
} else if (c == dist[v]) cnt[v] = (cnt[v] + cnt[u]) % mod;
}
}
return cnt[n - 1];
}
};
```
[⬆ Back to top](#table-of-contents)
## 142. Sort List
Solution
```cpp
class Solution {
ListNode* splitList(ListNode *head) {
ListNode dummy, *p = &dummy, *q = &dummy;
dummy.next = head;
while (q && q->next) {
q = q->next->next;
p = p->next;
}
auto next = p->next;
p->next = NULL;
return next;
}
ListNode *mergeList(ListNode *a, ListNode *b) {
ListNode head, *tail = &head;
while (a && b) {
ListNode *node;
if (a->val <= b->val) {
node = a;
a = a->next;
} else {
node = b;
b = b->next;
}
tail->next = node;
tail = node;
}
if (a) tail->next = a;
if (b) tail->next = b;
return head.next;
}
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
auto b = splitList(head);
return mergeList(sortList(head), sortList(b));
}
};
```
[⬆ Back to top](#table-of-contents)
## 143. Frog Position After T Seconds
Solution
```cpp
class Solution {
public:
vector > G;
vector seen;
int target;
double frogPosition(int n, vector>& edges, int t, int target) {
if (n == 1) return 1.0;
this->target = target;
G.resize(n + 1, vector());
for (auto e : edges) {
int u = e[0], v = e[1];
G[u].push_back(v);
G[v].push_back(u);
}
seen = vector(n + 1, false);
return dfs(1, t);
}
double dfs(int i, int t) {
// When time finishes and adjacent list is of size 1.
if (i != 1 && G[i].size() == 1 || t == 0) {
return i == target;
}
seen[i] = true;
double res = 0;
for (auto j : G[i]) {
if (! seen[j]) {
res += dfs(j, t - 1);
}
}
return res / (G[i].size() - (i != 1));
}
};
```
[⬆ Back to top](#table-of-contents)
## 144. Longest Zigzag Path In A Binary Tree
Solution
```cpp
class Solution {
int A = 0;
pair postorder(TreeNode* root) {
if (!root || (!root->left && !root->right)) return { 0, 0 };
pair ans;
if (root->left) {
auto left = postorder(root->left);
ans.first = 1 + left.second;
}
if (root->right) {
auto right = postorder(root->right);
ans.second = 1 + right.first;
}
A = max({ A, ans.first, ans.second });
return ans;
}
public:
int longestZigZag(TreeNode* root) {
postorder(root);
return A;
}
};
```
[⬆ Back to top](#table-of-contents)
## 145. Balance A Binary Seach Tree
Solution
```cpp
class Solution {
vector v;
void inorder(TreeNode *root) {
if (!root) return;
inorder(root->left);
v.push_back(root->val);
inorder(root->right);
}
TreeNode *build(int start, int end) {
if (start >= end) return NULL;
int mid = (start + end) / 2;
auto node = new TreeNode(v[mid]);
node->left = build(start, mid);
node->right = build(mid + 1, end);
return node;
}
public:
TreeNode* balanceBST(TreeNode* root) {
inorder(root);
return build(0, v.size());
}
};
```
[⬆ Back to top](#table-of-contents)
## 146. Linked List in Binary Tree
Solution
```cpp
class Solution {
bool match(ListNode *head, TreeNode *root) {
if (!head) return true;
if (!root) return false;
if (head->val != root->val) return false;
return match(head->next, root->left) || match(head->next, root->right);
}
public:
bool isSubPath(ListNode* head, TreeNode* root) {
if (!head) return true;
if (!root) return false;
if (match(head, root)) return true;
return isSubPath(head, root->left) || isSubPath(head, root->right);
}
};
```
[⬆ Back to top](#table-of-contents)
## 147. Find Substring With Given Hash Value
Solution 1
```cpp
class Solution {
public:
string subStrHash(string s, int p, int mod, int k, int target) {
long h = 0, N = s.size(), pp = 1; // `pp` = p^k
vector hash(N);
string r(rbegin(s), rend(s));
for (int i = 0; i < N; ++i) {
h = (h * p + (r[i] - 'a' + 1)) % mod; // push r[i] into the window
if (i < k) pp = pp * p % mod;
else h = (h - (r[i - k] - 'a' + 1) * pp % mod + mod) % mod; // pop r[i-k] out of the window
if (i >= k - 1) hash[i] = h;
}
reverse(begin(hash), end(hash));
for (int i = 0; i < N; ++i) {
if (hash[i] == target) return s.substr(i, k);
}
return "";
}
};
```
Solution 2
```cpp
class Solution {
public:
string subStrHash(string s, int p, int M, int k, int target) {
long h = 0, pp = 1;
int N = s.size();
vector hash(N);
string r(rbegin(s), rend(s));
for (int i = 0 ; i < N; i++) {
h = (h * p + (r[i] - 'a' + 1)) % M;
if (i < k) {
pp = (pp * p) % M;
} else {
h = (h - (r[i - k] - 'a' + 1) * pp % M + M) % M;
}
if (i >= k - 1) {
hash[i] = h;
}
}
reverse(hash.begin(), hash.end());
for (int i = 0; i < N; i++) {
if (hash[i] == target) {
return s.substr(i, k);
}
}
return "";
}
};
```
[⬆ Back to top](#table-of-contents)
## 148. Distinct Echo Substrings
Solution
```cpp
class Solution {
public:
int distinctEchoSubstrings(string s) {
int M = 1e8 + 7, cnt = 0;
int N = s.length();
vector hash(N);
for (int len = 1; len <= N / 2; len++) {
long h = s[0] - 'a', p = 1;
unordered_set visited;
for (int i = 1; i < N; i++) {
if (i < len) {
h = (h * 26 + s[i] - 'a') % M;
p = (p * 26) % M;
} else {
h = ((h - (s[i - len] - 'a') * p) * 26 + s[i] - 'a') % M;
if (h < 0) h += M;
if ( i - 2 * len + 1 >= 0 && hash[i - len] == h) {
auto a = s.substr(i - 2 * len + 1, len);
if (visited.count(a)) continue;
visited.insert(a);
if (a == s.substr(i - len + 1, len)) cnt++;
}
}
hash[i] = h;
}
}
return cnt;
}
};
```
[⬆ Back to top](#table-of-contents)
## 149. Longest Duplicate Substring
Solution
```cpp
class Solution {
public:
int findDuplicate(string s, int len) {
int N = s.length();
unsigned long long h = 0, d = 12582917, p = 1;
unordered_set visited;
for (int i = 0; i < N; i++) {
h = h * d + s[i];
if (i < len) {
p *= d;
} else {
h -= s[i - len] * p;
}
if ( i >= len - 1) {
if (visited.count(h)) return i - len + 1;
visited.insert(h);
}
}
return -1;
}
string longestDupSubstring(string s) {
int L = 0, R = s.size() - 1, start = 0;
while (L < R) {
int M = (L + R + 1) / 2;
int i = findDuplicate(s, M);
if (i != -1) {
L = M;
start = i;
} else {
R = M - 1;
}
}
return s.substr(start, L);
}
};
```
[⬆ Back to top](#table-of-contents)
## 150. Distribute Coins In Binary Tree
Solution
```cpp
class Solution {
private:
int ans = 0;
int postorder(TreeNode *root) {
if (!root) return 0;
int move = 1 - root->val + postorder(root->left) + postorder(root->right);
ans += abs(move);
return move;
}
public:
int distributeCoins(TreeNode* root) {
postorder(root);
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 151. Range Sum Query - Mutable
Solution
```cpp
struct segtree {
vector sums;
int size;
void init(int n) {
size = 1;
while (size < n) size *= 2;
sums.assign(size * 2, 0LL);
}
void set(int i, int v, int x, int lx, int rx) {
if (rx - lx == 1) {
sums[x] = v;
return;
}
int m = (lx + rx) / 2;
if (i < m) {
set(i, v, 2 * x + 1, lx, m);
} else {
set(i, v, 2 * x + 2, m, rx);
}
sums[x] = sums[2 * x + 1] + sums[2 * x + 2];
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
long long sum(int l, int r, int x, int lx, int rx) {
// no intersection
if (lx >= r || l >= rx) return 0;
// inside
if (lx >= l && rx <= r) return sums[x];
int m = (lx + rx) / 2;
long long s1 = sum(l, r, 2 * x + 1, lx, m);
long long s2 = sum(l, r, 2 * x + 2, m, rx);
return s1 + s2;
}
long long sum(int l, int r) {
return sum(l, r, 0, 0, size);
}
};
class NumArray {
public:
NumArray(vector& nums) {
n = nums.size();
st.init(n);
for (int i = 0; i < n; i++) {
st.set(i, nums[i]);
}
}
void update(int index, int val) {
st.set(index, val);
}
int sumRange(int left, int right) {
return st.sum(left, right + 1);
}
private:
segtree st;
int n;
};
```
[⬆ Back to top](#table-of-contents)
## 152. Shortest Palindrome
Solution
```cpp
class Solution {
public:
string shortestPalindrome(string s) {
unsigned d = 16777619, h = 0, rh = 0, p = 1, maxLen = 0;
for (int i = 0; i < s.size(); ++i) {
h = h * d + s[i] - 'a';
rh += (s[i] - 'a') * p;
p *= d;
if (h == rh) maxLen = i + 1;
}
return string(rbegin(s), rbegin(s) + s.size() - maxLen) + s;
}
};
```
[⬆ Back to top](#table-of-contents)
## 153. Maximum Number of Events That Can Be Attended
Solution
```cpp
int maxEvents(vector>& events) {
sort(events.begin(), events.end());
int i = 0, N = events.size(), eventAttended = 0;
int day = events[0][0];
priority_queue, greater<>> pq;
while (i < N || pq.size()) {
if (pq.empty()) day = events[i][0];
while (i < N && events[i][0] == day) pq.push(events[i++][1]);
pq.pop();
eventAttended++;
day++;
while (pq.size() && pq.top() < day) pq.pop();
}
return eventAttended;
}
```
[⬆ Back to top](#table-of-contents)
## 154. Maximum Product of The Length of Two Palindromic Substrings
Solution
```cpp
// Ref: https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/discuss/1389958/Manacher-and-Queue
class Solution {
public:
long long maxProduct(string s) {
int N = s.size(), j = 0;
vector r(N, 1);
for (int i = 1; i < N; ++i) {
int cur = j + r[j] > i ? min(r[2 * j - i], j + r[j] - i) : 1;
while (i - cur >= 0 && i + cur < N && s[i - cur] == s[i + cur]) ++cur;
if (i + cur > j + r[j]) j = i;
r[i] = cur;
}
vector right(N, 1); // right[i] is the length of the longest palinedome in [i, n)
queue> q, q1; // index, range
for (int i = N - 1; i >= 0; --i) {
while (q.size() && q.front()[0] - q.front()[1] >= i) q.pop(); // if the queue front's range can't cover `i`, pop it.
q.push({i, r[i]});
right[i] = 1 + (q.front()[0] - i) * 2; // now queue front is the rightmost range that can cover `i`. It must be the center of the longest palindrom in `[i, n)`.
}
int left = 0; // left is the length of the longest palindrome in [0, i].
long long ans = 1;
for (int i = 0; i < N - 1; ++i) {
while (q1.size() && q1.front()[0] + q1.front()[1] <= i) q1.pop();
q1.push({i, r[i]});
left = max(left, 1 + (i - q1.front()[0]) * 2);
ans = max(ans, (long long)left * right[i + 1]);
}
return ans;
}
};
```
[⬆ Back to top](#table-of-contents)
## 155. Repeated DNA Sequences
Solution
```cpp
vector findRepeatedDnaSequences(string s) {
int N = s.size();
unordered_map hash;
vector ans;
if (N <= 10) return ans;
long long p = 5, h = 0, M = 1e9 + 7, d = 1;
for (int i = N - 1; i >= 0; i--) {
h = (h * p) % M + (s[i] - 'A' + 1) % M;
if (i + 10 >= N) {
d = (d * p) % M;
} else {
h = (h - ((s[i + 10] - 'A' + 1) * d) % M + M) % M;
}
if (hash.find(h) != hash.end() && hash[h] == 1) {
ans.push_back(s.substr(i, 10));
}
hash[h]++;
}
return ans;
}
```
[⬆ Back to top](#table-of-contents)
## 156. K Divisible Elements Subarray
Solution
```cpp
class Solution {
public:
int countDistinct(vector& nums, int k, int p) {
int base = 211, N = nums.size();
unordered_setS;
for (int i = 0; i < N; i++) {
unsigned long long hash = 0;
int countDivisible = 0;
for (int j = i; j < N; j++) {
hash = hash * base + nums[j];
countDivisible += (nums[j] % p == 0);
if (countDivisible <= k) {
S.insert(hash);
} else {
break;
}
}
}
return (int)(S.size());
}
};
struct Trie {
unordered_map ch;
int cnt = 0;
int insert(vector& nums, int i, int k, int p) {
if (i == nums.size() || k - (nums[i] % p == 0) < 0)
return 0;
if (ch[nums[i]] == nullptr)
ch[nums[i]] = new Trie();
return (++ch[nums[i]]->cnt == 1) +
ch[nums[i]]->insert(nums, i + 1, k - (nums[i] % p == 0), p);
}
};
int countDistinct(vector& nums, int k, int p) {
int res = 0;
Trie t;
for (int i = 0; i < nums.size(); ++i)
res += t.insert(nums, i, k, p);
return res;
}
```
[⬆ Back to top](#table-of-contents)
## 157. Problem Name
Solution
```cpp
```
[⬆ Back to top](#table-of-contents)
================================================
FILE: solutions/base-conversion.md
================================================
# Base Conversion
## Find Unique Binary String
- Conversion of String to Number via stoi()
- Use of bitset
```cpp
class Solution {
public:
string findDifferentBinaryString(vector& nums) {
unordered_set integers;
for (string num : nums) {
integers.insert(stoi(num, 0, 2));
}
int n = nums.size();
for (int num = 0; num <= n; num++) {
if (integers.find(num) == integers.end()) {
string ans = bitset<16>(num).to_string();
return ans.substr(16 - n);
}
}
return "";
}
};
```
================================================
FILE: solutions/bellman-ford.md
================================================
# Bellman Ford Algorithm
## Cheapest Flights Within K Stops
```cpp
class Solution {
public:
int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) {
vector dist(n, 1e9);
dist[src] = 0;
// K relaxation
for(int i = 0; i <= k; i++) {
auto temp = dist;
for(auto &e : flights) {
int u = e[0], v = e[1], w = e[2];
dist[v] = min(dist[v], temp[u] + w);
}
}
if(dist[dst] == 1e9) {
return -1;
} else {
return dist[dst];
}
}
};
```
## Network Delay Time
```cpp
class Solution {
public:
int networkDelayTime(vector>& times, int n, int k) {
vector dist(n, 1e9);
dist[k - 1] = 0;
for(int i = 0; i < n; i++) {
for(auto &e : times) {
int u = e[0] - 1, v = e[1] - 1, w = e[2];
if(dist[u] != 1e9) {
dist[v] = min(dist[v], dist[u] + w);
}
}
}
int answer = *max_element(dist.begin(), dist.end());
if(answer == 1e9) {
return -1;
} else {
return answer;
}
}
};
```
================================================
FILE: solutions/binary-trees.md
================================================
================================================
FILE: solutions/bit-manipulation.md
================================================
- [Bit Manipulation](#bit-manipulation)
- [17. Number of One bits](#17-number-of-one-bits)
# Bit Manipulation
## 17. Number of One bits
```cpp
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while(n) {
n = n & (n - 1);
ans++;
}
return ans;
}
};
```
================================================
FILE: solutions/custom-comparator.md
================================================
# Custom Comparator
## Sort Array By Parity
```cpp
vector sortArrayByParity(vector& nums) {
sort(nums.begin(), nums.end(), [&](int a, int b) {
return (a % 2) < (b % 2);
});
return nums;
}
```
## Sort The People
```cpp
vector sortPeople(vector& names, vector& heights) {
int N = names.size();
vector idx(N, 0);
iota(idx.begin(), idx.end(), 0);
sort(idx.begin(), idx.end(), [&](int i, int j) {
return heights[i] > heights[j];
});
vector ans;
for (auto &a : idx) {
ans.push_back(names[a]);
}
return ans;
}
```
## Bitwise XOR of All Pairings
View Code
```cpp
class Solution {
public:
int xorAllNums(vector& nums1, vector& nums2) {
int ans = 0;
int M = nums1.size(), N = nums2.size();
if (N & 1) {
ans = accumulate(nums1.begin(), nums1.end(), 0, [](int x, int y) {
return x ^ y;
});
}
if (M & 1) {
ans ^= accumulate(nums2.begin(), nums2.end(), 0, [](int x, int y) {
return x ^ y;
});
}
return ans;
}
};
```
================================================
FILE: solutions/design.md
================================================
# Design and Implementation
## Implement Queue Using Stack
```cpp
class MyQueue {
public:
stack S1, S2;
void push(int x) {
while(S1.size()) {
S2.push(S1.top());
S1.pop();
}
S2.push(x);
while(S2.size()) {
S1.push(S2.top());
S2.pop();
}
}
int pop() {
int x = S1.top();
S1.pop();
return x;
}
int peek() {
return S1.top();
}
bool empty() {
return S1.empty();
}
};
```
## Implement Stack Using Queue
```cpp
class MyStack {
public:
queue q1, q2;
void push(int x) {
q2.push(x);
while(q1.size()) {
q2.push(q1.front());
q1.pop();
}
while(q2.size()) {
q1.push(q2.front());
q2.pop();
}
}
int pop() {
int x = q1.front();
q1.pop();
return x;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};
```
## Stock Price Fluctuation
```cpp
class StockPrice {
map m;
multiset s;
public:
StockPrice() {}
void update(int t, int p) {
if (m.count(t)) {
s.erase(s.find(m[t]));
}
m[t] = p;
s.insert(p);
}
int current() {
return m.rbegin()->second;
}
int maximum() {
return *s.rbegin();
}
int minimum() {
return *s.begin();
}
};
```
## Time based Key-Value Store
```cpp
class TimeMap {
public:
unordered_map>> M;
void set(string key, string value, int timestamp) {
M[key][timestamp] = value;
}
string get(string key, int timestamp) {
if (M.count(key) == 0) return "";
auto it = M[key].lower_bound(timestamp);
if(it == M[key].end()) {
return "";
} else {
return it->second;
}
}
};
```
## Design Circular Queue
```cpp
class MyCircularQueue {
private:
vector v;
int start = 0, len = 0;
public:
MyCircularQueue(int k): v(k) {}
bool enQueue(int value) {
if (isFull()) return false;
v[(start + len++) % v.size()] = value;
return true;
}
bool deQueue() {
if (isEmpty()) return false;
start = (start + 1) % v.size();
--len;
return true;
}
int Front() {
if (isEmpty()) return -1;
return v[start];
}
int Rear() {
if (isEmpty()) return -1;
return v[(start + len - 1) % v.size()];
}
bool isEmpty() {
return !len;
}
bool isFull() {
return len == v.size();
}
};
```
================================================
FILE: solutions/dfs.md
================================================
# DFS
## 13. Restore the Array From Adjacent Pairs
```cpp
class Solution {
public:
unordered_map> graph;
vector restoreArray(vector>& adjacentPairs) {
for (auto &edge: adjacentPairs) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
int root = 0;
for (auto &[a, b] : graph) {
if (b.size() == 1) {
root = a;
}
}
vector ans;
dfs(root, INT_MAX, ans);
return ans;
}
void dfs(int start, int prev, vector&ans) {
ans.push_back(start);
for (int neighbours: graph[start]) {
if (neighbours != prev) {
dfs(neighbours, start, ans);
}
}
}
};
```
================================================
FILE: solutions/dijksta.md
================================================
- [Dijkstra's Algorithm](#dijkstras-algorithm)
- [1. Network Delay Time](#1-network-delay-time)
- [2. Cheapest Flights Within K Stops](#2-cheapest-flights-within-k-stops)
- [3. Path With Minimum Effort](#3-path-with-minimum-effort)
- [9. Minimum Cost To Make Atleast One Valid Path In Graph](#9-minimum-cost-to-make-atleast-one-valid-path-in-graph)
- [11. Design Graph With Shortest Path Calculator](#11-design-graph-with-shortest-path-calculator)
# Dijkstra's Algorithm
## 1. Network Delay Time
View Code
```cpp
class Solution {
typedef pair PII;
public:
int networkDelayTime(vector>& E, int n, int k) {
vector> G(n);
for (auto &e : E) G[e[0] - 1].emplace_back(e[1] - 1, e[2]);
vector dist(n, INT_MAX);
dist[k - 1] = 0;
priority_queue, greater<>> pq;
pq.emplace(0, k - 1);
while (pq.size()) {
auto [cost, u] = pq.top();
pq.pop();
if (dist[u] > cost) continue;
for (auto &[v, w] : G[u]) {
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.emplace(dist[v], v);
}
}
}
int ans = *max_element(begin(dist), end(dist));
return ans == INT_MAX ? -1 : ans;
}
};
```
## 2. Cheapest Flights Within K Stops
View Code
```cpp
class Solution {
public:
int findCheapestPrice(int n, vector>& flights, int src, int dst, int k) {
// Creation of Graph
vector>> G(n);
for(auto &e : flights) {
int u = e[0], v = e[1], w = e[2];
G[u].push_back({v, w});
}
k++;
// Cost, CityID, Stops left
priority_queue, vector>, greater<>> pq;
pq.push({0, src, k});
//Minimum distance
vector> dist(k + 1, vector(n, INT_MAX));
for (int i = 0; i <= k; i++) {
dist[i][src] = 0;
}
while (pq.size()) {
auto [c, u, stop] = pq.top();
pq.pop();
if (c > dist[stop][u]) continue;
if (u == dst) return c;
if (stop == 0) continue;
for (auto &[v, w] : G[u]) {
int newCost = c + w;
if (dist[stop - 1][v] > newCost) {
dist[stop - 1][v] = newCost;
pq.push({newCost, v, stop - 1});
}
}
}
return -1;
}
};
```
## 3. Path With Minimum Effort
View Code
```cpp
class Solution {
public:
int dirs[4][2] = { {0, 1}, {1, 0}, {-1, 0}, {0, -1}};
int minimumEffortPath(vector>& A) {
int M = A.size(), N = A[0].size();
vector> dist(M, vector(N, INT_MAX));
priority_queue, vector>, greater<>> pq;
pq.push({0, 0, 0});
dist[0][0] = 0;
while (pq.size()) {
auto [cost, a, b] = pq.top();
pq.pop();
if (cost > dist[a][b]) continue;
if (a == M - 1 && b == N - 1) return cost;
for(auto &dir : dirs) {
int x = a + dir[0];
int y = b + dir[1];
if (x < 0 || y < 0 || x >= M || y >= N) continue;
int newCost = max(cost, abs(A[a][b] - A[x][y]));
if (newCost < dist[x][y]) {
dist[x][y] = newCost;
pq.push({newCost, x, y});
}
}
}
return dist[M - 1][N - 1];
}
};
```
## 9. Minimum Cost To Make Atleast One Valid Path In Graph
```cpp
class Solution {
public:
int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int minCost(vector>& grid) {
int M = grid.size(), N = grid[0].size();
int dist[100][100] = {};
memset(dist, 0x3f, sizeof(dist));
// Cost, X, Y
priority_queue, vector>, greater<>> pq;
pq.push({0, 0, 0});
dist[0][0] = 0;
while (pq.size()) {
auto [cost, x, y] = pq.top();
pq.pop();
if (cost > dist[x][y]) continue;
if (x == M - 1 && y == N - 1) return cost;
for (int i = 0; i < 4; i++) {
int a = x + dirs[i][0];
int b = y + dirs[i][1];
if (a < 0 || b < 0 || a >= M || b >= N) continue;
int newCost = cost + (grid[x][y] != i + 1);
if (dist[a][b] > newCost) {
dist[a][b] = newCost;
pq.push({newCost, a, b});
}
}
}
return 0;
}
};
```
## 11. Design Graph With Shortest Path Calculator
```cpp
class Graph {
public:
vector>> adj;
Graph(int n, vector>& edges) {
adj.resize(n);
for (auto &e: edges) {
adj[e[0]].push_back(make_pair(e[1], e[2]));
}
}
void addEdge(vector edge) {
adj[edge[0]].push_back(make_pair(edge[1], edge[2]));
}
int shortestPath(int node1, int node2) {
// Implement Dijkstra
int n = adj.size();
priority_queue, vector>, greater>> pq;
vector dist(n, INT_MAX);
dist[node1] = 0;
pq.push(make_pair(0, node1));
while (!pq.empty()) {
int d = pq.top().first, node = pq.top().second;
pq.pop();
if (node == node2) return d;
if (d > dist[node]) continue;
for (auto &neighbour: adj[node]) {
int newDistance = d + neighbour.second;
if (newDistance < dist[neighbour.first]) {
dist[neighbour.first] = newDistance;
pq.push(make_pair(newDistance, neighbour.first));
}
}
}
return -1;
}
};
```
================================================
FILE: solutions/dp.md
================================================
- [Dynamic Programming](#dynamic-programming)
- [Climbing Stairs](#climbing-stairs)
- [Pascal's Triangle](#pascals-triangle)
- [Best Time To Buy and Sell Stock](#best-time-to-buy-and-sell-stock)
- [Jump Game](#jump-game)
- [Unique Paths](#unique-paths)
- [Decode Ways](#decode-ways)
- [Maximum Product Subarray](#maximum-product-subarray)
- [House Robber](#house-robber)
- [Word Break](#word-break)
- [Coin Change](#coin-change)
# Dynamic Programming
## Climbing Stairs
View Code
```cpp
int climbStairs(int n) {
if(n == 1) return 1;
vector dp(n, 0);
dp[0] = 1;
dp[1] = 2;
for(int i = 2; i < n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n - 1];
}
```
## Pascal's Triangle
View Code
```cpp
class Solution {
public:
vector> generate(int N) {
vector> ans(N);
for(int i = 0; i < N; i++) {
ans[i] = vector(i + 1, 1);
for(int j = 1; j < i; j++) {
ans[i][j] = ans[i - 1][j] + ans[i - 1][j - 1];
}
}
return ans;
}
};
```
## Best Time To Buy and Sell Stock
View Code
```cpp
class Solution {
public:
int maxProfit(vector& prices) {
int N = prices.size();
int minStock = prices[0];
int profit = 0;
for(int i = 0; i < N; i++) {
minStock = min(minStock, prices[i]);
profit = max(profit, prices[i] - minStock);
}
return profit;
}
};
```
## Jump Game
View Code
```cpp
class Solution {
public:
bool canJump(vector& nums) {
int N = nums.size();
int maxEnd = 0;
for(int i = 0; i < N && maxEnd >= i; i++) {
maxEnd = max(maxEnd, i + nums[i]);
}
return maxEnd >= N - 1;
}
};
```
## Unique Paths
View Code
```cpp
class Solution {
public:
int uniquePaths(int m, int n) {
vector dp(n + 1, 0);
dp[n - 1] = 1;
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--){
dp[j] += dp[j + 1];
}
}
return dp[0];
}
};
```
## Decode Ways
View Code
```cpp
class Solution {
public:
int numDecodings(const string& s) {
int N = s.size();
vector dp(N + 1, 0);
dp[N] = 1;
for (int i = N - 1; i >= 0; --i) {
if (s[i] != '0') {
dp[i] += dp[i + 1];
}
if (i+1 < N && (s[i] == '1' || s[i] == '2' && s[i + 1] <= '6')) {
dp[i] += dp[i + 2];
}
}
return dp[0];
}
};
```
## Maximum Product Subarray
View Code
```cpp
class Solution {
public:
int maxProduct(vector& nums) {
int maxProd = 1, minProd = 1;
int ans = INT_MIN;
for (int n : nums) {
int a = maxProd * n;
int b = minProd * n;
maxProd = max({n, a, b});
minProd = min({n, a, b});
ans = max(ans, maxProd);
}
return ans;
}
};
```
## House Robber
View Code
```cpp
class Solution {
public:
int rob(vector& nums) {
int N = nums.size();
int rob = nums[0], notRob = 0;
for (int i = 1; i < N; i++) {
int temp = notRob;
notRob = rob;
rob = max(rob, temp + nums[i]);
}
return max(rob, notRob);
}
};
```
## Word Break
View Code
```cpp
class Solution {
public:
bool wordBreak(string s, vector& wordDict) {
unordered_set M(wordDict.begin(), wordDict.end());
int N = s.length();
vector dp(N + 1, false);
dp[0] = true;
for (int i = 1; i <= N; i++) {
for (int j = 0; j < i && !dp[i]; j++) {
dp[i] = dp[j] && M.count(s.substr(j, i - j));
}
}
return dp[N];
}
};
```
## Coin Change
View Code
```cpp
class Solution {
public:
int coinChange(vector& coins, int amount) {
int N = coins.size();
sort(coins.begin(), coins.end());
vector dp(amount + 1, INT_MAX);
dp[0] = 0;
for (int j = 1; j <= amount; j++) {
dp[j] = INT_MAX;
for (auto coin : coins) {
if (j - coin < 0) break;
if (dp[j - coin] != INT_MAX) {
dp[j] = min(dp[j], 1 + dp[j - coin]);
}
}
}
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
};
```
================================================
FILE: solutions/euler-circuit.md
================================================
# Euler Circuit
## Reconstruct Itinerary
View Code
```cpp
class Solution {
public:
vector findItinerary(vector>& E) {
unordered_map> G;
for (auto &e : E) G[e[0]].insert(e[1]);
vector ans;
function euler = [&](string u) {
while (G[u].size()) {
auto v = *G[u].begin();
G[u].erase(G[u].begin());
euler(v);
}
ans.push_back(u);
};
euler("JFK");
return vector(rbegin(ans), rend(ans));
}
};
```
## Cracking The Safe
View Code
```cpp
class Solution {
public:
string crackSafe(int n, int k) {
if(n == 1 && k == 1) return "0";
unordered_set M;
string start = string(n - 1, '0');
string ans = "";
function euler = [&](string u) {
for(char c = '0'; c < k + '0'; c++) {
string v = u + c;
if(M.count(v)) continue;
M.insert(v);
euler(v.substr(1));
ans.push_back(c);
}
};
euler(start);
return ans + start;
}
};
```
## Valid Arrangement of Pairs
View Code
```cpp
class Solution {
public:
vector> validArrangement(vector>& pairs) {
unordered_map> G;
unordered_map indegrees, outdegrees;
for(auto &e : pairs) {
int u = e[0], v = e[1];
G[u].push_back(v);
indegrees[v]++;
outdegrees[u]++;
}
// Select the starting node.
int start = -1;
for(auto &[u, ad] : G ) {
if(outdegrees[u] - indegrees[u] == 1) {
start = u;
break;
}
}
if(start == -1) {
start = pairs[0][0];
}
vector> ans;
function euler = [&](int u) {
auto &ad = G[u];
while(ad.size()) {
int v = ad.back();
ad.pop_back();
euler(v);
ans.push_back({u, v});
}
};
euler(start);
reverse(ans.begin(), ans.end());
return ans;
}
};
```
================================================
FILE: solutions/fenwick-tree.md
================================================
================================================
FILE: solutions/heaps/kth-largest-element-in-array.md
================================================
## Kth Largest Element in Array
```cpp
class Solution {
public:
int findKthLargest(vector& nums, int k) {
priority_queue, greater<>> pq;
for(auto N : nums) {
pq.push(N);
if(pq.size() > k) {
pq.pop();
}
}
return pq.top();
}
};
```
================================================
FILE: solutions/heaps/sort-array-by-increasing-frequency.md
================================================
## Sort Array By Increasing Frequency
```cpp
class Solution {
public:
vector frequencySort(vector& nums) {
unordered_map cnt;
for(int n : nums) cnt[n]++;
auto cmp = [&](int a, int b) {
if(cnt[a] == cnt[b]) {
return a < b;
}
return cnt[a] > cnt[b];
};
priority_queue, decltype(cmp)> pq(cmp);
for(auto &[n, c] : cnt) {
pq.push(n);
}
vector ans;
while(pq.size()) {
int c = pq.top();
pq.pop();
while(cnt[c]--) {
ans.push_back(c);
}
}
return ans;
}
};
```
================================================
FILE: solutions/heaps/sort-characters-by-frequency.md
================================================
## Sort Characters By Frequency
```cpp
class Solution {
public:
string frequencySort(string s) {
unordered_map cnt;
for(char c : s) {
cnt[c]++;
}
auto cmp = [&](char a, char b) { return cnt[a] < cnt[b]; };
priority_queue, decltype(cmp)> pq(cmp);
for(auto &[c, n] : cnt) {
pq.push(c);
}
string ans = "";
while(pq.size()) {
char c = pq.top();
pq.pop();
ans += string(cnt[c], c);
}
return ans;
}
};
```
================================================
FILE: solutions/heaps/top-k-frequent-elements.md
================================================
## Top K Frequent Elements
```cpp
class Solution {
public:
vector topKFrequent(vector& nums, int k) {
unordered_map cnt;
auto cmp = [&](int a, int b) { return cnt[a] > cnt[b]; };
priority_queue, decltype(cmp)> pq(cmp);
for(int n : nums) cnt[n]++;
for(auto &[n, c] : cnt) {
pq.push(n);
}
vector ans;
while(pq.size() > k) {
int c = pq.top();
pq.pop();
}
while(pq.size()) {
int c = pq.top();
pq.pop();
ans.push_back(c);
}
return ans;
}
};
```
================================================
FILE: solutions/intervals.md
================================================
# Intervals
## Merge Intervals
View Code
```cpp
class Solution {
public:
vector> merge(vector>& A) {
sort(A.begin(), A.end());
vector> ans;
for(auto &a : A) {
if(ans.empty() || a[0] > ans.back()[1]) {
ans.push_back(a);
} else {
ans.back()[1] = max(a[1], ans.back()[1]);
}
}
return ans;
}
};
```
## Insert Interval
View Code
```cpp
class Solution {
public:
vector> insert(vector>& intervals, vector& newInterval) {
int start = newInterval[0], end = newInterval[1];
vector> ans;
for(auto &intv : intervals) {
// Four cases
if(start > end) {
ans.push_back(intv);
} else if(end < intv[0]) {
ans.push_back({start, end});
start = end + 1;
ans.push_back(intv);
} else if(start > intv[1]) {
ans.push_back(intv);
} else {
// Update start and end
start = min(start, intv[0]);
end = max(end, intv[1]);
}
}
if(start <= end) {
ans.push_back({start, end});
}
return ans;
}
};
```
## Non Overlapping Interval
View Code
```cpp
class Solution {
public:
int eraseOverlapIntervals(vector>& intervals) {
sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) {
return a[1] < b[1];
});
int overlapCnt = 0;
int end = INT_MIN;
for(auto &e : intervals) {
if(e[0] >= end) {
end = e[1];
} else {
overlapCnt++;
}
}
return overlapCnt;
}
};
```
## Minimum Number of Arrows To Burst Balloons
View Code
```cpp
class Solution {
public:
int findMinArrowShots(vector>& points) {
sort(points.begin(), points.end(), [](auto &a, auto &b) {
return a[1] < b[1];
});
long end = LONG_MIN;
long answer = points.size();
for(auto &p : points) {
if(p[0] <= end) {
answer--;
} else {
end = p[1];
}
}
return answer;
}
};
```
## My Calendar I
View Code
```cpp
class MyCalendar {
public:
MyCalendar() {
}
map M;
bool book(int start, int end) {
if(M.empty()) {
M[start] = end;
return true;
}
// Conditions
auto it = M.upper_bound(start);
// Check the later intersection
if(it != M.end() && it->first < end) return false;
// Check the starting intersection
if(it != M.begin() && prev(it)->second > start) return false;
// After checking conditions
M[start] = end;
return true;
}
};
```
## Video Stitching
View Code
```cpp
class Solution {
public:
int videoStitching(vector>& clips, int time) {
sort(clips.begin(), clips.end());
int N = clips.size();
int ans = 0;
for(int i = 0, st = 0, end = 0; st < time; st = end, ans++) {
while(i < N && clips[i][0] <= st) {
end = max(end, clips[i++][1]);
}
if(st == end) {
return -1;
}
}
return ans;
}
};
```
================================================
FILE: solutions/kruskal.md
================================================
# Kruskal Algorithm
## Min Cost To Connect All Points
View Code
```cpp
class UnionFind {
private:
vector id, rank;
int cnt;
public:
UnionFind(int cnt) : cnt(cnt) {
id = vector(cnt);
rank = vector(cnt, 0);
for (int i = 0; i < cnt; ++i) id[i] = i;
}
int find(int p) {
if (id[p] == p) return p;
return id[p] = find(id[p]);
}
int getCount() {
return cnt;
}
bool connected(int p, int q) {
return find(p) == find(q);
}
void connect(int p, int q) {
int i = find(p), j = find(q);
if (i == j) return;
if (rank[i] < rank[j]) {
id[i] = j;
} else {
id[j] = i;
if (rank[i] == rank[j]) rank[j]++;
}
--cnt;
}
};
class Solution {
public:
int minCostConnectPoints(vector>& points) {
int N = points.size();
vector> E;
for(int i = 0; i < N; i++) {
for(int j = i + 1; j < N; j++) {
E.push_back({abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]), i, j});
}
}
UnionFind uf(N);
int ans = 0;
// How to convert vector into heap.
make_heap(E.begin(), E.end(), greater>());
while(uf.getCount() > 1) {
pop_heap(E.begin(), E.end(), greater>());
auto [w, u, v] = E.back();
E.pop_back();
if(uf.connected(u, v)) continue;
uf.connect(u, v);
ans += w;
}
return ans;
}
};
```
## Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
View Code
```cpp
class UnionFind {
vector id;
int size;
public:
UnionFind(int N) : id(N), size(N) {
iota(begin(id), end(id), 0);
}
int find(int x) {
return id[x] == x ? x : (id[x] = find(id[x]));
}
bool connect(int x, int y) {
int p = find(x), q = find(y);
if (p == q) return false;
id[p] = q;
--size;
return true;
}
int getSize() { return size; }
};
class Solution {
int kruskal(int n, vector> &E, int include = -1, int exclude = -1) {
int cost = 0;
UnionFind uf(n);
if (include != -1) {
auto &e = E[include];
uf.connect(e[0], e[1]);
cost += e[2];
}
for (int i = 0; i < E.size(); ++i) {
if (i == include || i == exclude) continue;
int u = E[i][0], v = E[i][1], w = E[i][2], id = E[i][3];
if (!uf.connect(u, v)) continue;
cost += w;
if (uf.getSize() == 1) break;
}
return uf.getSize() == 1 ? cost : INT_MAX;
}
public:
vector> findCriticalAndPseudoCriticalEdges(int n, vector>& E) {
for (int i = 0; i < E.size(); ++i) E[i].push_back(i);
sort(begin(E), end(E), [](vector &a, vector &b) { return a[2] < b[2]; });
int cost = kruskal(n, E);
vector c, p;
for (int i = 0; i < E.size(); ++i) {
if (kruskal(n, E, -1, i) > cost) c.push_back(E[i][3]);
else if (kruskal(n, E, i) == cost) p.push_back(E[i][3]);
}
return { c, p };
}
};
```
================================================
FILE: solutions/line-sweep.md
================================================
================================================
FILE: solutions/linked-list.md
================================================
================================================
FILE: solutions/lis.md
================================================
================================================
FILE: solutions/manacher.md
================================================
================================================
FILE: solutions/matrix.md
================================================
================================================
FILE: solutions/merge-sort.md
================================================
================================================
FILE: solutions/prefix-state-map.md
================================================
# Prefix State Map
## Contiguous Array
View Code
```cpp
class Solution {
public:
int findMaxLength(vector& A) {
unordered_map M;
int N = A.size();
int sum = 0, ans = 0;
M[0] = -1;
for(int i = 0; i < N; i++) {
sum += A[i] == 1 ? 1 : -1;
if(M.count(sum)) {
ans = max(ans, i - M[sum]);
} else {
M[sum] = i;
}
}
return ans;
}
};
```
## Find the Longest Substring Containing Vowels in Even Counts
View Code
```cpp
class Solution {
public:
int findTheLongestSubstring(string s) {
int ans = 0;
int N = s.length();
int h = 0;
unordered_map m{{'a', 0}, {'e', 1}, {'i', 2}, {'o', 3}, {'u', 4}};
unordered_map index{{0, -1}};
for(int i = 0; i < N; i++) {
if(m.count(s[i])) {
h ^= (1 << m[s[i]]);
}
if(index.count(h)) {
ans = max(ans, i - index[h]);
} else {
index[h] = i;
}
}
return ans;
}
};
```
## Number of Wonderful Substrings
View Code
```cpp
class Solution {
public:
long long wonderfulSubstrings(string s) {
int N = s.size(), mask = 0;
long long ans = 0, m[1024] = {1};
for (int i = 0; i < N; ++i) {
mask ^= 1 << (s[i] - 'a');
ans += m[mask];
for (int j = 0; j < 10; ++j) {
int next = mask ^ (1 << j);
ans += m[next];
}
m[mask]++;
}
return ans;
}
};
```
## Find Longest Awesome Substring
View Code
```cpp
class Solution {
public:
int longestAwesome(string s) {
map M;
M[0] = -1;
int N = s.length(), ans = 0;
for(int i = 0, mask = 0; i < N; i++) {
mask ^= (1 << (s[i] - '0'));
if(M.count(mask)) ans = max(ans, i - M[mask]);
else M[mask] = i;
for(int j = 0; j < 10; j++) {
int prev = mask ^ (1 << j);
if(M.count(prev)) ans = max(ans, i - M[prev]);
}
}
return ans;
}
};
```
================================================
FILE: solutions/queries.md
================================================
================================================
FILE: solutions/rolling-hash/distinct-echo-substrings.md
================================================
## Distinct Echo Substrings
```cpp
class Solution {
public:
int distinctEchoSubstrings(string s) {
int M = 1e8 + 7, cnt = 0;
int N = s.length();
vector hash(N);
for (int len = 1; len <= N / 2; len++) {
long h = s[0] - 'a', d = 1, p = 26;
unordered_set visited;
for (int i = 1; i < N; i++) {
if (i < len) {
h = (h * p + s[i] - 'a') % M;
d = (d * p) % M;
} else {
h = ((h - (s[i - len] - 'a') * d) * p + s[i] - 'a') % M;
if (h < 0) h += M;
if ( i - 2 * len + 1 >= 0 && hash[i - len] == h) {
auto a = s.substr(i - 2 * len + 1, len);
if (visited.count(a)) continue;
visited.insert(a);
if (a == s.substr(i - len + 1, len)) cnt++;
}
}
hash[i] = h;
}
}
return cnt;
}
};
```
================================================
FILE: solutions/rolling-hash/find-substring-with-given-hash-value.md
================================================
## Find Substring With Given Hash Value
```cpp
class Solution {
public:
string subStrHash(string s, int p, int M, int k, int target) {
long h = 0, pp = 1;
int N = s.size();
vector hash(N);
string r(rbegin(s), rend(s));
for (int i = 0 ; i < N; i++) {
h = (h * p + (r[i] - 'a' + 1)) % M;
if (i < k) {
pp = (pp * p) % M;
} else {
h = (h - (r[i - k] - 'a' + 1) * pp % M + M) % M;
}
if (i >= k - 1) {
hash[i] = h;
}
}
reverse(hash.begin(), hash.end());
for (int i = 0; i < N; i++) {
if (hash[i] == target) {
return s.substr(i, k);
}
}
return "";
}
};
```
================================================
FILE: solutions/rolling-hash/k-divisible-elements-subarray.md
================================================
## K Divisible Elements Subarray
```cpp
class Solution {
public:
int countDistinct(vector& nums, int k, int p) {
int P = 211, N = nums.size();
unordered_setS;
for (int i = 0; i < N; i++) {
unsigned long long h = 0;
int countDivisible = 0;
for (int j = i; j < N; j++) {
h = h * P + nums[j];
countDivisible += (nums[j] % p == 0);
if (countDivisible <= k) {
S.insert(h);
} else {
break;
}
}
}
return (int)(S.size());
}
};
```
================================================
FILE: solutions/rolling-hash/longest-common-subpath.md
================================================
## Longest Common Subpath
```cpp
```
================================================
FILE: solutions/rolling-hash/longest-duplicate-substring.md
================================================
## Longest Duplicate Substring
```cpp
```
================================================
FILE: solutions/rolling-hash/repeated-dna-sequences.md
================================================
## Repeated DNA Sequences
```cpp
vector findRepeatedDnaSequences(string s) {
int N = s.size();
unordered_map hash;
vector ans;
if (N <= 10) return ans;
long long p = 5, h = 0, M = 1e9 + 7, d = 1;
for (int i = N - 1; i >= 0; i--) {
h = (h * p) % M + (s[i] - 'A' + 1) % M;
if (i + 10 >= N) {
d = (d * p) % M;
} else {
h = (h - ((s[i + 10] - 'A' + 1) * d) % M + M) % M;
}
if (hash.find(h) != hash.end() && hash[h] == 1) {
ans.push_back(s.substr(i, 10));
}
hash[h]++;
}
return ans;
}
```
================================================
FILE: solutions/rolling-hash/shortest-palindrome.md
================================================
## Shortest Palindrome
```cpp
class Solution {
public:
string shortestPalindrome(string s) {
unsigned d = 16777619, h = 0, rh = 0, p = 1, maxLen = 0;
for (int i = 0; i < s.size(); ++i) {
h = h * d + s[i] - 'a';
rh += (s[i] - 'a') * p;
p *= d;
if (h == rh) maxLen = i + 1;
}
return string(rbegin(s), rbegin(s) + s.size() - maxLen) + s;
}
};
```
================================================
FILE: solutions/rolling-hash/sum-of-scores-of-built-strings.md
================================================
## Sum of Scores of Built Strings
```cpp
```
================================================
FILE: solutions/segment-tree.md
================================================
# Segment Tree
- [Segment Tree](#segment-tree)
- [Sum of Even Numbers After Queries](#sum-of-even-numbers-after-queries)
- [Range Sum Query Mutable](#range-sum-query-mutable)
- [Longest Increasing Subsequence - II](#longest-increasing-subsequence---ii)
- [Shifting Letters - II](#shifting-letters---ii)
- [Falling Squares](#falling-squares)
## Sum of Even Numbers After Queries
```cpp
struct segtree {
int size;
vector sums;
void init(int n) {
size = 1;
while (size < n) size *= 2;
sums.assign(2 * size, 0);
}
void set(int i, int v, int x, int lx, int rx) {
if (rx - lx == 1){
sums[x] = v % 2 == 0 ? v : 0;
return;
}
int m = (lx + rx) / 2;
if (i < m) set(i, v, 2 * x + 1, lx, m);
else set(i, v, 2 * x + 2, m, rx);
sums[x] = sums[2 * x + 1] + sums[2 * x + 2];
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
int sum(int l, int r, int x, int lx, int rx) {
if (lx >= r || l >= rx) return 0;
if (lx >= l && rx <= r) return sums[x];
int m = (lx + rx) / 2;
int s1 = sum(l, r, 2 * x + 1, lx, m);
int s2 = sum(l, r, 2 * x + 2, m, rx);
return s1 + s2;
}
int sum(int l, int r) {
return sum(l, r, 0, 0, size);
}
};
class Solution {
public:
vector sumEvenAfterQueries(vector& nums, vector>& queries) {
int n = nums.size();
segtree st;
st.init(n);
for (int i = 0; i < n; i++) st.set(i, nums[i]);
vector ans;
for (auto q : queries) {
int val = q[0], idx = q[1];
st.set(idx, nums[idx] += val);
ans.push_back(st.sum(0, n));
}
return ans;
}
};
```
## Range Sum Query Mutable
```cpp
struct segtree {
vector sums;
int size;
void init(int n) {
size = 1;
while (size < n) size *= 2;
sums.assign(size * 2, 0LL);
}
void set(int i, int v, int x, int lx, int rx) {
if (rx - lx == 1) {
sums[x] = v;
return;
}
int m = (lx + rx) / 2;
if (i < m) {
set(i, v, 2 * x + 1, lx, m);
} else {
set(i, v, 2 * x + 2, m, rx);
}
sums[x] = sums[2 * x + 1] + sums[2 * x + 2];
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
long long sum(int l, int r, int x, int lx, int rx) {
if (lx >= r || l >= rx) return 0;
if (lx >= l && rx <= r) return sums[x];
int m = (lx + rx) / 2;
long long s1 = sum(l, r, 2 * x + 1, lx, m);
long long s2 = sum(l, r, 2 * x + 2, m, rx);
return s1 + s2;
}
long long sum(int l, int r) {
return sum(l, r, 0, 0, size);
}
};
class NumArray {
public:
NumArray(vector& nums) {
n = nums.size();
st.init(n);
for (int i = 0; i < n; i++) {
st.set(i, nums[i]);
}
}
void update(int index, int val) {
st.set(index, val);
}
int sumRange(int left, int right) {
return st.sum(left, right + 1);
}
private:
segtree st;
int n;
};
```
## Longest Increasing Subsequence - II
```cpp
struct segtree {
vector a;
int size;
void init(int n) {
size = 1;
while (size < n) size *= 2;
a.assign(size * 2, 0LL);
}
void set(int i, int v, int x, int lx, int rx) {
if (rx - lx == 1) {
a[x] = v;
return;
}
int m = (lx + rx) / 2;
if (i < m) set(i, v, 2 * x + 1, lx, m);
else set(i, v, 2 * x + 2, m, rx);
a[x] = max(a[2 * x + 1], a[2 * x + 2]);
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
long long op(int l, int r, int x, int lx, int rx) {
if (lx >= r || l >= rx) return 0;
if (lx >= l && rx <= r) return a[x];
int m = (lx + rx) / 2;
return max(op(l, r, 2 * x + 1, lx, m), op(l, r, 2 * x + 2, m, rx));
}
long long op(int l, int r) {
return op(l, r, 0, 0, size);
}
};
class Solution {
public:
int lengthOfLIS(vector& nums, int k) {
segtree st;
int n = nums.size(), ans = 0;
st.init(1e5 + 5);
for (auto x : nums) {
// look for max of LIS from [x - k, x]
int mx = st.op(max(0, x - k), x);
ans = max(ans, mx + 1);
st.set(x, mx + 1);
}
return ans;
}
};
```
## Shifting Letters - II
```cpp
class Solution {
public:
vector seg;
void upd(int l, int r, int v, int x, int lx, int rx) {
if(lx > r or rx < l) return;
if(lx >= l and rx <= r) {
seg[x] += v;
return;
}
int mid = (lx + rx) / 2;
upd(l, r, v, 2 * x + 1, lx, mid);
upd(l, r, v, 2 * x + 2, mid + 1, rx);
}
int query(int i, int x, int lx, int rx) {
if(lx == rx) return seg[x];
int mid = (lx + rx) / 2;
if(i <= mid)
return seg[x] + query(i, 2 * x + 1, lx, mid);
return seg[x] + query(i, 2 * x + 2, mid + 1, rx);
}
string shiftingLetters(string s, vector>& shifts) {
long x = 1;
while(x <= s.length()) x <<= 1;
seg.resize(2 * x, 0);
for(int i = 0; i < shifts.size(); ++i) {
int l = shifts[i][0], r = shifts[i][1], dir;
if(shifts[i][2] == 0) dir = -1;
else dir = 1;
upd(l, r, dir, 0, 0, x - 1);
}
for(int i = 0; i < s.length(); ++i) {
int shift = query(i, 0, 0, x - 1);
int dir = (shift > 0) ? 1 : -1;
shift = abs(shift) % 26;
shift *= dir;
int cur = s[i] - 'a';
cur = (cur + shift + 26) % 26;
s[i] = char(cur + 'a');
}
return s;
}
};
```
## Falling Squares
```cpp
class Solution {
vector tree;
int N = 0;
void updateAt(int i, int val) {
i += N;
tree[i] = val;
while (i > 0) {
i /= 2;
tree[i] = max(tree[2 * i], tree[2 * i + 1]);
}
}
void update(int begin, int end, int val) {
for (int i = begin; i < end; ++i) updateAt(i, val);
}
int maxRange(int i, int j) {
i += N;
j += N;
int ans = 0;
while (i <= j) {
if (i % 2) ans = max(ans, tree[i++]);
if (j % 2 == 0) ans = max(ans, tree[j--]);
i /= 2;
j /= 2;
}
return ans;
}
public:
vector fallingSquares(vector> & positions) {
vector a;
for (auto& p : positions) {
a.push_back(p[0]);
a.push_back(p[0] + p[1]);
}
sort(a.begin(), a.end());
N = unique(a.begin(), a.end()) - a.begin();
a.resize(N);
tree.resize(2 * N + 1);
vector res;
for (auto& p : positions) {
int l = lower_bound(a.begin(), a.end(), p[0]) - a.begin();
int r = lower_bound(a.begin(), a.end(), p[0] + p[1]) - a.begin();
int maxh = maxRange(l, r - 1);
update(l, r, maxh + p[1]);
res.push_back(maxRange(0, N));
}
return res;
}
};
```
```cpp
struct segtree {
vector a;
int size;
void init(int n) {
size = 1;
while (size < n) size *= 2;
a.assign(size * 2, 0LL);
}
void set(int i, int v, int x, int lx, int rx) {
if (rx - lx == 1) {
a[x] = v;
return;
}
int m = (lx + rx) / 2;
if (i < m) set(i, v, 2 * x + 1, lx, m);
else set(i, v, 2 * x + 2, m, rx);
a[x] = max(a[2 * x + 1], a[2 * x + 2]);
}
void set(int i, int v) {
set(i, v, 0, 0, size);
}
long long op(int l, int r, int x, int lx, int rx) {
if (lx >= r || l >= rx) return 0;
if (lx >= l && rx <= r) return a[x];
int m = (lx + rx) / 2;
return max(op(l, r, 2 * x + 1, lx, m), op(l, r, 2 * x + 2, m, rx));
}
long long op(int l, int r) {
return op(l, r, 0, 0, size);
}
};
class Solution {
public:
vector fallingSquares(vector>& positions) {
int N;
vector a;
for (auto& p : positions) {
a.push_back(p[0]);
a.push_back(p[0] + p[1]);
}
sort(a.begin(), a.end());
N = unique(a.begin(), a.end()) - a.begin();
a.resize(N);
segtree st;
st.init(2 * N + 1);
// tree.resize(2 * N + 1);
vector res;
for (auto& p : positions) {
int l = lower_bound(a.begin(), a.end(), p[0]) - a.begin();
int r = lower_bound(a.begin(), a.end(), p[0] + p[1]) - a.begin();
int maxh = st.op(l, r);
for (int i = l; i < r; i++) {
st.set(i, maxh + p[1]);
};
res.push_back(st.op(0, N + 1));
}
return res;
}
};
```
================================================
FILE: solutions/sets.md
================================================
# Sets
## 1. Find All Numbers Disappeared in an Array
```cpp
class Solution {
public:
vector findDisappearedNumbers(vector& nums) {
int n = nums.size();
// Erase Duplicates from given array
sort(nums.begin(), nums.end());
nums.erase(unique(nums.begin(), nums.end()), nums.end());
// Generate another vector from [1 ... n]
vector v(n);
iota(v.begin(), v.end(), 1);
// Which elements of v are not included in nums
vector notIncluded;
set_difference(v.begin(), v.end(), nums.begin(), nums.end(), back_inserter(notIncluded));
return notIncluded;
}
};
```
================================================
FILE: solutions/sieve-eratosthenes.md
================================================
# Sieve of Eratosthenes
## Count Primes
View Code
```cpp
class Solution {
public:
int countPrimes(int n) {
vector primes(n + 1, true);
int cntPrimes = 0;
for(int i = 2; i < n; i++) {
if(!primes[i]) continue;
cntPrimes++;
for(int j = i; j < n; j += i) {
primes[j] = false;
}
}
return cntPrimes;
}
};
```
## Four Divisors
View Code
```cpp
class Solution {
int num = 100001;
void sieve_div(vector &v, unordered_map& m){
for (int i = 1; i < num; i++) {
for (int j = i; j < num; j += i){
v[j]++;
m[j] += i;
}
}
}
public:
int sumFourDivisors(vector& nums) {
long ans=0;
vector v(num, 0);
unordered_map m;
sieve_div(v, m);
int n = nums.size();
for (int i = 0; i < n; i++) {
if (v[nums[i]] == 4){
ans += m[nums[i]];
}
}
return ans;
}
};
```
================================================
FILE: solutions/sliding-window/count-subarrays-with-fixed-count.md
================================================
## Count Subarrays With Fixed Count
```cpp
long long countSubarrays(vector& A, int minK, int maxK) {
long res = 0, jbad = -1, jmin = -1, jmax = -1, n = A.size();
for (int i = 0; i < n; ++i) {
if (A[i] < minK || A[i] > maxK) jbad = i;
if (A[i] == minK) jmin = i;
if (A[i] == maxK) jmax = i;
res += max(0L, min(jmin, jmax) - jbad);
}
return res;
}
```
================================================
FILE: solutions/sliding-window.md
================================================
# Sliding Window
## Longest Substring Without Repeating Characters
```cpp
int lengthOfLongestSubstring(string s) {
int N = s.length();
int ans = 0, i = 0;
unordered_map M;
for(int j = 0; j < N; j++) {
M[s[j]]++;
// Window size increases from left side.
while(M[s[j]] > 1) {
M[s[i++]]--;
}
ans = max(ans, j - i + 1);
}
return ans;
}
```
## Minimum Size Subarray Sum
```cpp
int minSubArrayLen(int target, vector& nums) {
int N = nums.size();
int sum = 0, ans = N + 1, i = 0;
for(int j = 0; j < N; j++) {
sum += nums[j];
while(sum >= target) {
ans = min(ans, j - i + 1);
sum -= nums[i++];
}
}
return ans == N + 1 ? 0 : ans;
}
```
## Number of Smooth Descent Periods of a Stock
```cpp
long long getDescentPeriods(vector& prices) {
long long ans = 0;
int i = 0, N = prices.size();
for(int j = 0; j < N; j++) {
if(j && prices[j] + 1 != prices[j - 1]) {
i = j;
}
ans += (j - i + 1);
}
return ans;
}
```
## Frequency of Most Frequent Element
```cpp
int maxFrequency(vector& A, int k) {
sort(A.begin(), A.end());
int N = A.size();
long long i = 0, sum = 0, ans = 0;
for(int j = 0; j < N; j++) {
sum += A[j];
// Increase the windows size when our total sum - sum of window > k
while((A[j] * (j - i + 1) - sum) > k ) {
sum -= A[i++];
}
// If our window is valid, we can perform less than or equal to k operations.
ans = max(ans, j - i + 1);
}
return ans;
}
```
## Max Consecutive Ones III
```cpp
int longestOnes(vector& nums, int k) {
int N = nums.size();
int length = 0, i = 0, sum = 0;
for(int j = 0; j < N; j++) {
sum += nums[j];
while(((j - i + 1) - sum) > k) {
sum -= nums[i++];
}
length = max(length, j - i + 1);
}
return length;
}
```
================================================
FILE: solutions/stack.md
================================================
================================================
FILE: solutions/stringstream.md
================================================
================================================
FILE: solutions/sum-of-first-n-natural-numbers.md
================================================
## 1. Count Number of Homogenous Substrings
```cpp
class Solution {
public:
int countHomogenous(string s) {
int ans = 1;
int currentString = 1;
int MOD = 1e9 + 7;
for (int i = 1; i < s.length(); i++) {
if (s[i] == s[i - 1]) {
currentString++;
} else {
currentString = 1;
}
ans = (ans + currentString) % MOD;
}
return ans;
}
};
```
## 2. Number of Substrings With Only 1s
```cpp
class Solution {
public:
int numSub(string s) {
int ans = 0, MOD = 1e9 + 7;
int oneCount = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '1') {
oneCount++;
} else {
oneCount = 0;
}
ans = (ans + oneCount) % MOD;
}
return ans;
}
};
```
================================================
FILE: solutions/topological-sort.md
================================================
# Topological Sort
## Course Schedule
View Code
```cpp
class Solution {
public:
bool canFinish(int k, vector>& prerequisites) {
// Creation of Graph
unordered_map> G;
vector indegree(k, 0);
for (auto &e : prerequisites) {
int u = e[0], v = e[1];
G[v].push_back(u);
indegree[u]++;
}
// Queue to store the nodes with zero indegree - Topological Sort
queue q;
for (int i = 0; i < k; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
while (q.size()) {
int cnt = q.size();
while(cnt--) {
int u = q.front();
q.pop();
k--;
for(auto v : G[u]) {
if(--indegree[v] == 0) {
q.push(v);
}
}
}
}
return k == 0;
}
};
```
## Minimum Height Trees
View Code
```cpp
class Solution {
public:
vector findMinHeightTrees(int n, vector>& E) {
if (n == 1) return { 0 };
vector degree(n), ans;
vector> G(n);
for (auto &e : E) {
int u = e[0], v = e[1];
degree[u]++;
degree[v]++;
G[u].push_back(v);
G[v].push_back(u);
}
queue q;
for (int i = 0; i < n; ++i) {
if (degree[i] == 1) q.push(i);
}
while (n > 2) {
int cnt = q.size();
n -= cnt;
while (cnt--) {
int u = q.front();
q.pop();
for (int v : G[u]) {
if (--degree[v] == 1) q.push(v);
}
}
}
while (q.size()) {
ans.push_back(q.front());
q.pop();
}
return ans;
}
};
```
## Build A Matrix With Conditions
View Code
```cpp
class Solution {
public:
vector> buildMatrix(int k, vector>& rowConditions, vector>& colConditions) {
vector order1 = topologicalSort(k, rowConditions);
vector order2 = topologicalSort(k, colConditions);
if(order1.size() < k || order2.size() < k) return {};
// Mapping of column conditions.
unordered_map M;
for(int i = 0; i < k; i++) {
M[order2[i]] = i;
}
// Create a answer vector and return it.
vector> ans(k, vector(k, 0));
for(int i = 0; i < k; i++) {
ans[i][M[order1[i]]] = order1[i];
}
return ans;
}
vector topologicalSort(int k, vector> &A) {
// Degree
vector deg(k, 0), order;
// Creation of graph
vector> G(k, vector(0));
for(auto &c : A) {
int u = c[0], v = c[1];
G[u - 1].push_back(v - 1);
deg[v - 1]++;
}
queue q;
// Push node with indegree zero.
for(int i = 0; i < k; i++) {
if(deg[i] == 0) {
q.push(i);
}
}
while(q.size()) {
int x = q.front();
q.pop();
order.push_back(x + 1);
for(int &u : G[x]) {
if(--deg[u] == 0) {
q.push(u);
}
}
}
return order;
}
};
```
## Longest Increasing Path In Matrix
View Code
```cpp
class Solution {
public:
int longestIncreasingPath(vector>& A) {
int M = A.size(), N = A[0].size(), dirs[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}, ans = 0;
vector> indegree(M, vector(N));
queue> q;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
for (auto &[dx, dy] : dirs) {
int a = i + dx, b = j + dy;
if (a < 0 || b < 0 || a >= M || b >= N || A[a][b] >= A[i][j]) continue;
indegree[i][j]++;
}
if (indegree[i][j] == 0) q.push({ i, j });
}
}
while (q.size()) {
int cnt = q.size();
++ans;
while (cnt--) {
auto [x, y] = q.front();
q.pop();
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || b < 0 || a >= M || b >= N || A[a][b] <= A[x][y]) continue;
if (--indegree[a][b] == 0) q.push({ a, b });
}
}
}
return ans;
}
};
```
================================================
FILE: solutions/trie/concatenated-words.md
================================================
## Concatenated Words
```cpp
struct TrieNode {
TrieNode *next[26] = {};
bool end = false;
};
class Solution {
TrieNode root;
void addWord(TrieNode *node, string &s) {
for (char c : s) {
if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->end = true;
}
bool valid(string &s) {
int N = s.size();
vector dp(N + 1);
dp[0] = true;
for (int i = 0; i < N && !dp[N]; ++i) {
if (!dp[i]) continue;
auto node = &root;
for (int j = i; j < N - (i == 0); ++j) {
node = node->next[s[j] - 'a'];
if (!node) break;
if (node->end) dp[j + 1] = true;
}
}
return dp[N];
}
public:
vector findAllConcatenatedWordsInADict(vector& A) {
for (auto &s : A) {
if (s.empty()) continue;
addWord(&root, s);
}
vector ans;
for (auto &s : A) {
if (s.size() && valid(s)) ans.push_back(s);
}
return ans;
}
};
```
================================================
FILE: solutions/trie/implement-trie.md
================================================
## Implement Trie
```cpp
struct TrieNode {
TrieNode *next[26] = {};
bool isWord = false;
};
class Trie {
TrieNode root;
TrieNode* find(string s) {
auto node = &root;
for(char c : s) {
if(!node->next[c - 'a']) return NULL;
node = node->next[c - 'a'];
}
return node;
}
public:
void insert(string word) {
auto node = &root;
for(char c : word) {
if(!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->isWord = true;
}
bool search(string word) {
auto wordFind = find(word);
return wordFind && wordFind->isWord == true;
}
bool startsWith(string prefix) {
return find(prefix);
}
};
```
================================================
FILE: solutions/trie/k-divisible-elements-subarrays.md
================================================
## K Divisible Elements Subarray
```cpp
struct Trie {
unordered_map ch;
int cnt = 0;
int insert(vector& nums, int i, int k, int p) {
if (i == nums.size() || k - (nums[i] % p == 0) < 0) {
return 0;
}
if (ch[nums[i]] == nullptr) {
ch[nums[i]] = new Trie();
}
return (++ch[nums[i]]->cnt == 1) +
ch[nums[i]]->insert(nums, i + 1, k - (nums[i] % p == 0), p);
}
};
int countDistinct(vector& nums, int k, int p) {
int res = 0;
Trie t;
for (int i = 0; i < nums.size(); ++i) {
res += t.insert(nums, i, k, p);
}
return res;
}
```
================================================
FILE: solutions/trie/maximum-genetic-difference-query.md
================================================
## Maximum Genetic Difference Query
```cpp
struct TrieNode {
TrieNode *next[2] = {};
int cnt = 0;
};
class Solution {
public:
vector maxGeneticDifference(vector& P, vector>& Q) {
int N = P.size(), M = Q.size(), rootIndex;
vector> G(N);
for (int i = 0; i < N; ++i) {
if (P[i] != -1) G[P[i]].push_back(i);
else rootIndex = i;
}
unordered_map> m;
for (int i = 0; i < M; ++i) m[Q[i][0]].push_back(i);
TrieNode root;
auto getAnswer = [&](TrieNode *node, int q) {
int ans = 0;
for (int i = 31; i >= 0; --i) {
int b = q >> i & 1;
if (node->next[1 - b] && node->next[1 - b]->cnt) {
node = node->next[1 - b];
ans |= 1 << i;
} else node = node->next[b];
}
return ans;
};
vector ans(M);
function dfs = [&](int u) {
auto node = &root;
for (int i = 31; i >= 0; --i) {
int b = u >> i & 1;
if (!node->next[b]) node->next[b] = new TrieNode();
node = node->next[b];
node->cnt++;
}
if (m.count(u)) {
for (int index : m[u]) ans[index] = getAnswer(&root, Q[index][1]);
}
for (int v : G[u]) dfs(v);
node = &root;
for (int i = 31; i >= 0; --i) {
int b = u >> i & 1;
node = node->next[b];
node->cnt--;
}
};
dfs(rootIndex);
return ans;
}
};
```
================================================
FILE: solutions/trie/maximum-xor-of-two-numbers.md
================================================
## Maximum XOR of Two Numbers In An Array
```cpp
struct TrieNode {
TrieNode *next[2] = {};
};
class Solution {
void add(TrieNode *node, int n) {
for (int i = 31; i >= 0; --i) {
int b = n >> i & 1;
if (node->next[b] == NULL) node->next[b] = new TrieNode();
node = node->next[b];
}
}
int maxXor(TrieNode *node, int n) {
int ans = 0;
for (int i = 31; i >= 0; --i) {
int b = n >> i & 1;
if (node->next[1 - b]) { // if we can go the opposite direction, do it.
node = node->next[1 - b];
ans |= 1 << i;
} else {
node = node->next[b];
}
}
return ans;
}
public:
int findMaximumXOR(vector& A) {
TrieNode root;
int ans = 0;
for (int n : A) {
add(&root, n);
ans = max(ans, maxXor(&root, n));
}
return ans;
}
};
```
================================================
FILE: solutions/trie/palindrome-pairs.md
================================================
## Palindrome Pairs
```cpp
struct TrieNode {
TrieNode *next[26] = {};
int index = -1;
vector palindromeIndexes;
};
class Solution {
TrieNode root; // Suffix trie
void add(string &s, int i) {
auto node = &root;
for (int j = s.size() - 1; j >= 0; --j) {
if (isPalindrome(s, 0, j)) node->palindromeIndexes.push_back(i); // A[i]'s prefix forms a palindrome
int c = s[j] - 'a';
if (!node->next[c]) node->next[c] = new TrieNode();
node = node->next[c];
}
node->index = i;
node->palindromeIndexes.push_back(i); // A[i]'s prefix is empty string here, which is a palindrome.
}
bool isPalindrome(string &s, int i, int j) {
while (i < j && s[i] == s[j]) ++i, --j;
return i >= j;
}
public:
vector> palindromePairs(vector& A) {
int N = A.size();
for (int i = 0; i < N; ++i) add(A[i], i);
vector> ans;
for (int i = 0; i < N; ++i) {
auto s = A[i];
auto node = &root;
for (int j = 0; j < s.size() && node; ++j) {
if (node->index != -1 && node->index != i && isPalindrome(s, j, s.size() - 1)) ans.push_back({ i, node->index });
// A[i]'s prefix matches this word and A[i]'s suffix forms a palindrome
node = node->next[s[j] - 'a'];
}
if (!node) continue;
for (int j : node->palindromeIndexes) {
// A[i] is exhausted in the matching above.
// If a word whose prefix is palindrome after matching its suffix with A[i],
// then this is also a valid pair
if (i != j) ans.push_back({ i, j });
}
}
return ans;
}
};
```
================================================
FILE: solutions/trie/search-suggestions-system.md
================================================
## Search Suggestion System
```cpp
struct TrieNode {
TrieNode *next[26] = {};
int index = -1;
};
void add(TrieNode *node, string &product, int i) {
for(char c : product) {
if(!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->index = i;
}
void collect(TrieNode* node, vector &ans, vector &products) {
if(ans.size() == 3) return;
if(!node) return;
if(node->index > -1) ans.push_back(products[node->index]);
for(int i = 0; i < 26; i++) {
// Starting three valid words -> add them into answer -> return the function.
if(node->next[i]) {
collect(node->next[i], ans, products);
}
}
}
class Solution {
public:
vector> suggestedProducts(vector& products, string searchWord) {
TrieNode root, *node = &root;
int N = products.size();
vector> ans(searchWord.length());
for(int i = 0; i < N; i++) {
add(&root, products[i], i);
}
for(int i = 0; i < searchWord.length(); i++) {
node = node->next[searchWord[i] - 'a'];
if(!node) break;
// Collect three words from dictionary as per lexicographical order
collect(node, ans[i], products);
}
return ans;
}
};
```
================================================
FILE: solutions/trie/sum-of-prefix-scores-of-strings.md
================================================
## Sum of Prefix Scores of Strings
```cpp
struct TrieNode {
TrieNode *next[26] = {};
int cnt = 0;
};
class Solution {
TrieNode root;
public:
void insert(string word) {
auto node = &root;
for(char c : word) {
if(!node->next[c - 'a']) {
node->next[c - 'a'] = new TrieNode();
}
node->next[c - 'a']->cnt++;
node = node->next[c - 'a'];
}
}
int prefixCnt(string s) {
auto node = &root;
int ans = 0;
for(char c : s) {
ans += node->next[c - 'a']->cnt;
node = node->next[c - 'a'];
}
return ans;
}
vector sumPrefixScores(vector& words) {
int N = words.size();
// Insert words in trie.
for (int i = 0; i < N; i++) {
insert(words[i]);
}
vector ans(N, 0);
for (int i = 0; i < N; i++) {
// Get the count of all prefixes of given string.
ans[i] = prefixCnt(words[i]);
}
return ans;
}
};
```