blablabla
tags: matma, try also, cool python, cool c++, no number, tricky, string play, good practise in code base grep for 'cool read'
Template | 00 | | C++ Python| |
# | Title | Solution | Comments |
---|---|---|---|
1 | Two Sum | C++ | hash map, two pointers. Note that this is a special case (exactly one solution exists). So hash map works fine. In a general case sort + two pointers would work. |
2 | Add Two Numbers | C++ | classic linked list |
3 | Longest Substring Without Repeating Characters | C++ | sliding window |
4 | Median Of Two Sorted Arrays | C++ | can just merge the arrays, try also other solution which is tricky |
7 | Reverse Integer | C++ | as title |
8 | String To Integer | C C++ Python | as title |
10 | Regular Expression Matching | Python | check if s matches p, special chars * and . recursion, try also dp |
13 | Roman To Integer | Python | convert roman number to integer, use hash map |
14 | Longest Common Prefix | C++ | as title, get loops right |
15 | 3Sum | C++ | array of ints, find all unique triplets that sum to 0 |
17 | Letter Combinations Of A Phone Number | Python | cartesian product problem |
18 | 4Sum | Python | array of ints, find all unique quadruplets that sum to given target, used set to avoid duplicate quadruplets |
20 | Valid Parentheses | C Python | classic. stack. also assembly. |
22 | Generate Parentheses | Python | generate all valid combinations, recursion |
23 | Merge K Sorted Lists | C++ | as title, use priority queue |
24 | Swap Nodes In Pairs | C++ | swap nodes in linked list, play with pointers, good practise |
25 | Reverse Nodes In K-Group | C++ | linked list classic, can use recursion or an extra array |
28 | Implement strStr() | C | check if s1 is a substring of s2 |
29 | Divide Two Integers | C++ | as title, trick with bits |
30 | Substring With Concatenation Of All Words | C++ | within a string s find all concatenations of given set of strings of same size, two hash maps, try also sliding window |
31 | Next Permutation | Python | |
33 | Search In Rotated Sorted Array | C++ | binary search |
34 | Find First And Last Position Of Element In Sorted Array | Python | self descriptive, use bs |
37 | Sudoku Solver | Python | backtracking |
39 | Combination Sum | Python | given int array find combinations that sum up to target, unbound knapsack problem |
40 | Combination Sum II | Python | Given array of ints and target, find all unique combinations that sum to target. Each number in candidates may only be used once in the combination. Used tuple, try also without tuple. |
41 | First Missing Positive | Python | move values around i.e. '1' to index 0, '5' to index '6' etc |
42 | Trapping Rain Water | Python | classic, try also one pass solution |
45 | Jump Game II | C++ | same as 55 but here need to find out min number of jumps |
46 | Permutations | C++ Python | generate permutations, cool python |
47 | Permutations II | Python | generate permutations, input might contain duplicates |
48 | Rotate Image | Python | 2d matrix rotate by 90 degrees. just come up with an index convention |
49 | Group Anagrams | Python | sort + hash, string play |
50 | Pow(x,n) | Python | |
51 | N-Queens | Python | classic n queens problem, backtracking |
53 | Maximum Subarray | C++ | find the contiguous subarray which has the largest sum. Kadane algo. |
54 | Spiral Matrix | Python | my solution with O(N) space, try also O(1) space |
55 | Jump Game | Python | array of ints, each value max jump you can do from the current index, can you reach the last index |
60 | Permutation Sequence | C++ Python | basically directly find nth permutation |
61 | Rotate List | C++ | rotate linked list by k places |
62 | Unique Paths | C++ | dp |
63 | Unique Paths II | C++ | dp |
69 | Sqrt(x) | Python | bs, try also Newton |
70 | Climbing Stairs | Python | Need to reach nth step. Can climb 1 or 2 steps at a time. What's the number of ways to do it. Fibonacci |
73 | Set Matrix Zeroes | C++ Python | if 0 found, fill whole row and column with 0s. use only constant memory. |
74 | Search A 2D Matrix | Python | bs and mapping |
75 | Sort Colors | C++ Python | dutch partitioning problem, sort 3 colors in 1 pass with constant extra space |
76 | Minimum Window Substring | C++ | two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. sliding window. |
78 | Subsets | C++ Python | get all the subsets, bitmasks or recursion |
79 | Word Search | Python | check if word is in a grid, dfs |
84 | Largest Rectangle In Histogram | Python C++ | classic stack |
91 | Decode Ways | Python | string with digits given, mapping is 'a' -> 1, 'b' -> 2, ... 'z' -> 26, return number of ways to decode the string, dp |
93 | Restore IP Addresses | Python | string with digits, return all possible ips that can be created by adding dots, backtracking |
94 | Binary Tree Inorder Traversal | Python | iterative solutions |
95 | Unique Binary Search Trees II | C++ Python | given int n, return all structuraly unique bst trees with values 1 to n, similar to 96 |
96 | Unique Binary Search Trees | Python | how many structurally unique BSTs can you build |
97 | Interleaving String | C++ Python | check if s3 can be created by interleaving s1 and s2. dp |
98 | Validate Binary Search Tree | Python | as title, dfs |
99 | Recover Binary Search Tree | JS | find two swapped nodes in BST. in-order traversal |
101 | Symmetric Tree | C++ Python | recursive and iterative |
102 | Binary Tree Level Order Traversal | C++ Python | bfs or pre-order traversal |
104 | Maximum Depth Of Binary Tree | Python | as title |
105 | Construct Binary Tree From Preorder And Inorder Traversal | C++ | as title |
113 | Path Sum II | C++ Python | return all root-to-leaf paths where the sum equals targetSum. dfs or bfs |
114 | Flatten Binary Tree To Linked List | C++ Python | as title |
115 | Distinct Subsequences | Python | two strings s and t, return the number of distinct subsequences of s which equals t, dp |
116 | Populating Next Right Pointers In Each Node | C++ Python | as title |
118 | Pascals Triangle | Python | |
121 | Best Time To Buy And Sell Stock | C | |
122 | Best Time To Buy And Sell Stock II | C++ | at each step if profit can be made - do it |
123 | Best Time To Buy And Sell Stock III | C++ Python | 2 transactions allowed, my solution with 2 arrays |
124 | Binary Tree Maximum Path Sum | Python | recursion |
125 | Valid Palindrome | C++ | classic |
127 | Word Ladder | C++ Python | bidirectional bfs |
128 | Longest Consecutive Sequence | C++ Python | given unsorted array find the longest consecutive sequence (if the array was sorted) |
131 | Palindrome Partitioning | C++ Python | string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. dp |
133 | Clone Graph | C++ | use recursion and hash map. grafy |
134 | Gas Station | C++ | visiting a sequence of gas stations, where to start to complete the journey, greedy |
136 | Single Number | C++ | classic xor |
137 | Single Number II | C++ | traverse, keep adding bits on every position, divide modulo by three and voila |
138 | Copy List with Random Pointer | C++ Python | linked list, each node has an extra random pointer, make deep copy. Recursion or play with pointers and intertwine nodes |
139 | Word Break | C++ | dp |
140 | Word Break II | Python | dp |
141 | Linked List Cycle | C++ | classic, two pointers |
142 | Linked List Cycle II | C++ | Floyd's Tortoise and Hare cycle detection Algorithm |
144 | Binary Tree Preorder Traversal | Python | just Inorder Traversal a bit modified |
145 | Binary Tree Postorder Traversal | C++ | iterative solution |
146 | LRU Cache | C++ | |
150 | Evaluate Reverse Polish Notation | C++ Python | classic stack, cool c++ lambda |
151 | Reverse Words In A String | C++ C | |
153 | Find Minimum In Rotated Sorted Array | C++ | as title. bs |
154 | Find Minimum In Rotated Sorted Array II | C++ | duplicates allowed. bs |
155 | Min Stack | C++ | classic, with a trick we can use just one stack |
169 | Majority Element | C++ | Boyer–Moore majority vote algorithm |
173 | Binary Search Tree Iterator | C++ Python | generator in python |
174 | Dungeon Game | C++ Python | traverse grid, in each square you either gain or lose energy. what's the minimum start energy to finish. dp |
179 | Largest Number | C++ Python | array of non-negative ints give. Arrange themm so that they form largest number possible. Need a clever comparison operator |
188 | Best Time To Buy And Sell Stock IV | C++ Python | k transactions allowed |
189 | Rotate Array | C++ | |
190 | Reverse Bits | C++ | O(N) and O(1) solutions |
191 | Number Of1 Bits | C++ | find number of bits set to '1' in a given var, solution in O(N) N - number of '1's |
198 | House Robber | C++ | |
199 | Binary Tree Right Side View | C++ Python | dfs preorder traversal or bfs |
200 | Number Of Islands | C++ | count islands in a binary matrix |
204 | Count Primes | Python | Eratosthenes sieve |
205 | Isomorphic Strings | C++ Python | hash, string play |
207 | Course Schedule | Python | dfs |
208 | Implement Trie (Prefix Tree) | C++ | trie |
209 | Minimum Size Subarray Sum | C++ | as title. similar to 862 but easier |
210 | Course Schedule II | C++ | topological sort |
213 | House Robber II | Python | like a classic house robber but houses arranged in circle |
216 | Combination Sum III | Python | Find all valid combinations of k numbers that sum up to n. Only nums 1-9 can be used, and each num used at most once. |
218 | The Skyline Problem | Python | each building given as [leftX, rightX, height], return a set of points defining the skyline. use edges and heap |
221 | Maximal Square | Python | binary matrix with 0's and 1's, find largest square made of 1's. use dp. |
224 | Basic Calculator | Python | add, deduct and parenthesis |
226 | Invert Binary Tree | C++ | |
227 | Basic Calculator II | C++ Python | add, deduct, multiply and divide, cool C++ |
229 | Majority Element II | Python | Boyer–Moore majority vote algorithm |
230 | Kth Smallest Element in a BST | Python | do in-order traversal while counting |
232 | Implement Queue Using Stacks | C++ | use one stack for input and one for output |
236 | Lowest Common Ancestor Of A Binary Tree | C++ Python | as title, collect full paths to both nodes first and then easy solve, can be done easier |
238 | Product Of Array Except Self | C++ | int array 'a' given, create a new array 'b' where b[i] = a[0] * a[1] * ... * a[i-1] * a[i+1] * ... * a[sz-1] |
239 | Sliding Window Maximum | C++ Python | sliding window moving through an array, for each position find a median. multiset or heap or ind of monotonic deque |
258 | Add Digits | C++ Python | given int num, repeatedly add all its digits until the result has only one digit. can solve it by iteration, also solution in O(1) called digital root |
260 | Single Number III | C++ | in array all elements appear twice except two that appear once. find them. xor all, finda set bit and then extra pass to divide into 2 groups |
263 | Ugly Number | C++ | ugly number is a int whose prime factors are 2, 3, and 5. |
264 | Ugly Number II | C++ Python | find nth ugly number (that divides only by 2 3 and 5), dp |
268 | Missing Number | C++ | classic xor |
273 | Integer To English Words | Python | classic, recursion, try also word to integer |
274 | H-Index | C++ Python | definition of index h - if h of n papers have at least h citations each, and the other n − h papers have no more than h citations each. |
283 | Move Zeroes | C++ | in the array move all 0s to the end |
287 | Find The Duplicate Number | C++ Python | array has n+1 elements and values between 1 and n (inclusive). Find repeating element using only const space and not modifying the array. bits and marking, try also Floyd's cycle detection |
289 | Game Of Life | C++ | Cellular automaton. The values in the grid are only '0' and '1' so to solve it can just use other bits |
290 | Word Pattern | C++ | similar to isomorphic. hash map. |
292 | Nim Game | Python | heap of stones, players can remove 1,2, or 3. To win, you need to take the last stone |
295 | Find Median From Data Stream | C++ | two heaps and keep them balanced |
297 | Serialize And Deserialize Binary Tree | Python C++ | pre-order traversal works, not sure about formal proof, easy to see that post and in-order traversals not up to the task |
300 | Longest Increasing Subsequence | C++ Python | C++ solution easy dp in O(N^2), Python a bit tricky in O(NlnN), matma |
309 | Best Time To Buy And Sell Stock With Cooldown | Python C++ | |
312 | Burst Balloons | Python | burst ballons one by one, each time get score depending on neighbours, what's the max. dp |
313 | Super Ugly Number | C++ Python | given int n and list of primes, find nth ugly number. dp or heap |
315 | Count Of Smaller Numbers After Self | C++ Python | merge sort solution |
319 | Bulb Switcher | Python | bulbs go on and off, figure out the pattern, matma |
322 | Coin Change | C++ | classic dp, the fewest number of coins to make up the amount |
324 | Wiggle Sort II | C++ | Given an int array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... |
326 | Power Of Three | C++ | check if a given int is a power of 3 |
327 | Count Of Range Sum | Python | Given an int array and two ints lower and upper, return the number of range sums that lie in [lower, upper] inclusive. Prefix sum + merge sort |
328 | Odd Even Linked List | Python | rearrange nodes in list |
329 | Longest Increasing Path In A Matrix | Python | dfs with memiozation, try also topological sort |
332 | Reconstruct Itinerary | C++ Python | given a list of tickets reconstruct an itinerary. Eulerian path. Greedy dfs, build path backwards |
334 | Increasing Triplet Subsequence | Python | |
337 | House Robber III | C++ | house robber in a binary tree |
338 | Counting Bits | C++ | for a sequence of ints e.g 1,2,3,4,5 calculate mapping int - number of bits in binary representation |
342 | Power Of Four | C++ | check if given int is a power of 4, play with bits |
345 | Reverse Vowels Of A String | C++ Python | as title. good practise. |
347 | Top K Frequent Elements | C++ | as title. heap or bucket sort |
348 | Shuffle An Array | C++ | Fisher Yates Algorithm for random shuffling |
354 | Russian Doll Envelopes | C++ | kind of matryoshka problem with 2d envelopes. sort and then dp |
371 | Sum Of Two Integers | C++ | as title. bits manipulation. |
375 | Guess Number Higher Or Lower II | C++ | kind of minimax with transposition table/memoization |
380 | Insert Delete Get Random in O(1) | C++ | class to insert values, delete and get random |
394 | Decode String | Python | string encoded with ints, brackets and chars. use stack. |
395 | Longest Substring With At Least K Repeating Characters | C++ | string s and int k, return length of longest substring such that the frequency of each char in substring is greater than or equal to k. divide and conquer. |
396 | Rotate Function | Python | given array rotate it and calculate sum = arr0 * 0 + arr1 * 1 + ... , what rotation gives the biggest sum |
402 | Remove K Digits | C++ | for a given int remove K digits to get min value, greedy |
403 | Frog Jump | Python | array of ints gives mapping index to position, frog jumping, dp |
406 | Queue Reconstruction By Height | C++ Python | array of pairs (person's height, person's position in the original queue) given. Reconstruct the queue based on the array. |
407 | Trapping Rain Water II | C++ | classic in 3D. bfs with heap |
413 | Arithmetic Slices | Python | Gauss formula |
416 | Partition Equal Subset Sum | Python | can split array into two that have same sum, dp knapsack problem |
417 | Pacific Atlantic Water Flow | C++ | grid borders ocean A and ocean P. Values represent height. Find squares from which water can flow to both Oceans. bfs |
419 | Battleships In A Board | C++ | 2d board has 1d ships. Count them in one pass without modifying the board and using O(1) extra space. identify upper left corners of ships |
424 | Longest Repeating Character Replacement | C++ | similar to Max Consecutive Ones, sliding window |
437 | Path Sum III | C++ | in a binary tree find number of paths that sum to target, similar to Subarray Sum Equals K, hash map |
438 | Find All Anagrams In A String | C++ | 2 strings,get all indices of p anagrams in s.sliding window |
442 | Find All Duplicates In An Array | C++ | array of size n has values 1-n. some appear once and some twice. find duplicates. Cyclic sort |
445 | Add Two Numbers II | C++ | reverse linked list |
450 | Delete Node In A BST | C++ Python | dfs, find the node, if it has only left child - its easy, if it has both - find min value in the right child branch then easy |
451 | Sort Characters By Frequency | Python | |
453 | Minimum Number Of Arrows To Burst Balloons | Python | sort and greedy |
460 | LFU Cache | C++ Python | C++ solution optimal, Python stuff my more naive implementation |
462 | Minimum Moves To Equal Array Elements II | Python | in a move we can add or subtract 1 from an array element. min moves to make elements equal. matma. |
464 | Can I Win | C++ | game in which players alternate and take numbers from pool until a certain sum is reached, minimax with tt |
474 | Ones And Zeroes | C++ Python | given a set of binary strings. Pick as many as you can constraint being you end up with max total number of 0s m and 1s n, knapsack kind of in 2d, dp |
480 | Sliding Window Median | C++ | sliding window moving through an array, for each position find a maximum. multiset and try also 2 heaps |
493 | Reverse Pairs | C++ | merge sort solution |
494 | Target Sum | Python | given a sequence of ints, insert '+'s and '-'s to end up with target sum |
496 | Next Greater Element I | Python | classic stack |
498 | Diagonal Traverse | C++ Python | notice that if we add row and column of an element, we get an ID of a diagonal |
503 | Next Greater Element II | Python | given circular array find next greater number for every element, use stack |
516 | Longest Palindromic Subsequence | C++ | classic dp |
518 | Coin Change 2 | C++ | classic dp, the number of combinations that make up the amount |
530 | Minimum Absolute Difference In BST | C++ Python | as title, in-order traversal |
532 | K Diff Pairs In An Array | Python | find all unique pairs for which diff equals k |
539 | Minimum Time Difference | Python | convert to minutes and sort |
542 | 01 Matrix | Python | binary matrix, for each cell calculate distance from the neareast '0'. bfs. |
543 | Diameter Of Binary Tree | C++ | logest path between any two nodes. Solve it by finding depths of subtrees |
557 | Reverse Words In A String III | C++ C Python | as title, loops |
560 | Subarray Sum Equals K | Python | total number of continuous subarrays whose sum equals to k, use hashing |
575 | Distribute Candies | Python | n candies given, can be of different types, take half and maximize number of different types |
581 | Shortest Unsorted Continuous Subarray | Python | find the shortest subarray to sort to end up with the whole array sorted, sort or use monotonic stack |
583 | Delete Operation For Two Strings | C++ | given 2 strings w1 and w2, minimum number of steps to make them equal. dp |
594 | Longest Harmonious Subsequence | Python | a longest subsequence in which diff between min an max is exactly 1. hash map |
617 | Merge Two Binary Trees | C++ | as title says |
621 | Task Scheduler | Python C++ | python solution with heap and C++ more direct |
630 | Course Schedule III | C++ | Each course has duration and deadline. Cannot do 2 courses at the same time. What's the max number that can be taken. Sort and then heap. |
647 | Palindromic Substrings | Python | number of palindroms in a string, dp |
652 | Find Duplicate Subtrees | Python | serialise e.g. using pre-order traversal |
670 | Maximum Swap | Python | in given int swap two digits at most once to get maximum value, greedy |
680 | Valid Palindrome II | C++ | classic |
684 | Redundant Connection | C++ Python | build graph one edge at a time. Other solution brute force . grafy |
698 | Partition To K Equal Sum Subsets | C++ | as title. dp with bitmasks |
713 | Subarray Product Less Than K | Python | find number of subarrays where the product of all the elements is less than given k, sliding window |
714 | Best Time To Buy And Sell Stock With Transaction Fee | Python | |
718 | Maximum Length of Repeated Subarray | Python | two arrays given, longest common subarray, dp |
735 | Asteroid Collision | Python | classic stack problem with collisions |
738 | Monotone Increasing Digits | Python | Int has monotone increasing digits if each pair of adjacent digits x and y satisfy x <= y. Given int n, return largest int less or equal to n that has this characteristic. |
739 | Daily Temperatures | Python | for each day find number of days to wait for warmer temperature, use stack |
743 | Network Delay Time | C++ Python | Dijkstra's algorithm |
752 | Open The Lock | C++ | graph problem, bfs. grafy |
763 | Partition Labels | C++ | split array, got it on amzn interview |
765 | Couples Holding Hands | Python | Swap nums so that couples sit side by side. greedy, try also graph decomposition or union find. grafy |
766 | Toeplitz Matrix | C++ | matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements |
768 | Max Chunks To Make Sorted II | C++ Python | array of ints. split array. then sort each chunk and concatenate to end up with sorted array. what's the max number of chunks. use map or max / min. |
769 | Max Chunks To Make Sorted | Python | array of n ints contains values 0 to n-1 and no duplicates. split array. then sort each chunk and concatenate to end up with sorted array. what's the max number of chunks. |
779 | K Th Symbol In Grammar | C++ | start with 0, then in each round 0 turns into 01, 1 turns into 10, return Kth bit in Nth row, see pattern in tree and do recursion, try also one liner |
785 | Is Graph Bipartite | Python | can nodes be split into two groups and every edge connects these two groups, bfs or dfs. grafy |
787 | Cheapest Flights Within K Stops | Python | weighted graph given anf find the cheapest path from src to dst that has maximum K stops, dfs or bfs or other approaches. grafy |
790 | Domino And Tromino Tiling | C++ | number of ways to tile a board 2xn using dominos and trominos. dp |
829 | Consecutive Numbers Sum | C++ | number of ways an int can be written as a sum of consecutive ints. matma |
837 | New 21 Game | C++ Python | game with points, calculate probability |
838 | Push Dominoes | Python | dominoes falling, calculate final state. |
847 | Shortest Path Visiting All Nodes | C++ | given path return shortest path visiting all nodes, start at any node. cause not many nodes use bitmask and bfs |
854 | K-Similar Strings | C++ Python | A and B are anagrams, find min number of swaps in A to make it equal to B, backtracking or BFS |
862 | Shortest Subarray With Sum At Least K | Python | Given int array nums and int k, return the length of the shortest non-empty subarray of nums with a sum of at least k. Monotone queue |
870 | Advantage Shuffle | Python | advantage of arr1 over arr2 is number of indexes where value in arr1 is greater than in arr2. return permutation of arr1 that maximizes its advantage. sort + pointers |
871 | Minimum Number Of Refueling Stops | C++ | kind of jump game, heap or dp |
873 | Length Of Longest Fibonacci Subsequence | Python | brute force, try also dp |
875 | Koko Eating Bananas | C++ | max speed that satisfies a specific condition, use binary search |
877 | Stone Game | C++ | dp |
881 | Boats To Save People | C++ | each person has weight, there's a max weight per boat and boat can only take 2 people, how many boats we need. sort and greedy |
907 | Sum Of Subarray Minimums | Python | sum mins for all subarrays, use stack |
912 | Sort An Array | C++ Python | implemet some classic sort algos, heap sort and quicksort |
913 | Cat And Mouse | C++ | cat and mouse game on undirected graph. errichto dp top-down, try also other solutions. grafy |
931 | Minimum Falling Path Sum | Python | dp, similar to 1937 |
934 | Shortest Bridge | Python | grid with 2 islands, find the shortest bridge, bfs to expand island 1 until we hit island 2 |
938 | Minimum Cost For Tickets | C++ Python | array contains days on which i travel. i can buy 1, 7 or 30 days passes. find minimum i have to spend. dp |
950 | Reveal Cards In Increasing Order | C++ Python | arrange cards in a certain way |
954 | Array Of Doubled Pairs | C++ Python | re-arrange array so that each value has a pair twice as big |
956 | Tallest Billboard | C++ Python | given a set of rods construct supports for billboard, dp |
957 | Prison Cells After N Days | Python | cells become occupied or vacant, similar to bulbs, find cycle so we don't simulate it too many times |
958 | Check Completeness Of A Binary Tree | Python | as title. bfs. |
969 | Pancake Sorting | Python | should be self descriptive |
973 | K Closest Points To Origin | Python | as title. sorting. |
979 | Distribute Coins In Binary Tree | Python | re-distribute coins in tree so that every node has exactly one. dfs |
988 | Smallest String Starting From Leaf | C++ | dfs |
990 | Satisfiability Of Equality Equations | C++ | check if a set of equations with '!=' and '==' can be satisfied. classic dfs and union find |
991 | Broken Calculator | Python | go from int X to int Y, with min number of steps, can only multiply by 2 and subtract 1. go backwards from Y to X |
992 | Subarrays With K Different Integers | Python | int array nums and int k given, return the number of good subarrays. in good array number of different ints is exactly k. sliding window |
994 | Rotting Oranges | C++ | matrix problem, to solve do simulation |
996 | Number Of Squareful Arrays | C++ | find array permutations that would result in squarefl array, brute force or kind of Hamiltonian problem |
1004 | Max Consecutive Ones III | C++ | binary array and we can flip at most k '0's. What's the longest sequence of '1' we can get. Special case also solved in cpp file - what if only one '0' can be flipped. Classic sliding window. |
1007 | Minimum Domino Rotations For Equal Row | C++ | row of dominos give. If we can rotate some of them to get same value in a row, what's the minimum number of rotations. |
1008 | Construct Binary Search Tree From Preorder Traversal | C++ Python | as title. recursion. |
1024 | Video Stitching | Python | cut and stitch clips so they cover the whole interval, find min number of cuts to do it, sort and greedy |
1031 | Maximum Sum Of Two Non Overlapping Subarrays | C++ | title says it all also Alice and Bob picking Apples |
1048 | Longest String Chain | C++ | list of strings. given s1 you arrive at s2 by adding a char. find longest chain. dp bfs |
1081 | Smallest Subsequence Of Distinct Characters | Python | hashing and intuition |
1092 | Shortest Common Supersequence | C++ Python | Given two strings, return the shortest string that has both as subsequences. LCS. DFS + memiozation gets memory limit exceeded |
1109 | Corporate Flight Bookings | C++ | sweep line algo |
1110 | Delete Nodes And Return Forest | C++ | dfs |
1124 | Longest Well Performing Interval | Python | binary array, find longest subarray with more 1s than 0s, hashing to solve in linear time |
1143 | Longest Common Subsequence | Python | two strings and find LCS, dp |
1178 | Number Of Valid Words For Each Puzzle | C++ | string play. bitmasks. |
1186 | Maximum Subarray Sum With One Deletion | Python | Kadane algo twice - one forward and one backward |
1192 | Critical Connections In A Network | Python | removing what edges would result in disconnected graph. Tarjan's strongly connected components algorithm. grafy |
1209 | Remove All Adjacent Duplicates In String II | C++ | given string s and int k, do all k duplicate removals, stack |
1219 | Path With Maximum Gold | C++ | in grid find path with maximum gold. dfs. |
1221 | Split A String In Balanced Strings | C++ | split binary string in balanced substrings |
1222 | Queens That Can Attack The King | Python | given positions of king and queens, find queens that are attacking the king. solve by simulation. |
1239 | Maximum Length Of A Concatenated String With Unique Characters | C++ | glue strings together, needs to have unique chars, dfs + bitmasks, string play |
1244 | Design A Leaderboard | C++ | locked on lc, top K stocks on blmbrg interview, keep track of stocks traded and impement a function to print K most traded, hash map (to map stock to volume) and multimap (to map volume to stock) |
1247 | Minimum Swaps To Make Strings Equal | Python | two binary strings s1 and s2, can only swap chars between s1 and s2, minimum swaps to make them equal |
1249 | Minimum Remove To Make Valid Parentheses | C++ | stack solution |
1268 | Search Suggestions System | C++ | as title. good practise |
1305 | All Elements In Two Binary Search Trees | C++ | in-order traversal and merge |
1306 | Jump Game III | Python | can jump by arr[i] left or right, can we reach any index with value 0. recursion. |
1325 | Delete Leaves With A Given Value | C++ | dfs |
1338 | Reduce Array Size To The Half | C++ | Choose a set of ints from array and remove all their occurrences. Return the minimum size of the set so that at least half of the integers of the array are removed. Sort + greedy. |
1340 | Jump Game V | Python | jump to any index closer than d if no higher blocks between. max number of blocks to visit. sort + dp |
1345 | Jump Game IV | Python | can jump back or forward by 1 or to any index with the same value as the curren one. bfs |
1367 | Linked List In Binary Tree | C++ | bfs + dfs |
1368 | Cinema Seat Allocation | Python | as title. hash map and can use bitmasks |
1381 | Design A Stack With Increment Operation | C++ | stack with an operation that increments last k elements. lazy evaluation |
1382 | Balance A Binary Search Tree | C++ | given a root of BST, return a balanced BST, easy solution - in order traversal to collect numbers then construct balanced BST, try also DSW algorithm |
1395 | Count Number Of Teams | Python | basically in ints array find triplets that increase, in O(N^2) easy, try also balanced tree and bs |
1405 | Longest Happy String | C++ | string composed only of 'a', 'b', 'c'. Cannot have triplets (e.g. 'bbb'). Can have at most a occurences of 'a', b of 'b', c of 'c'.Construct longest possible. Similar to 621 (Task Scheduler) |
1442 | Count Triplets That Can Form Two Arrays Of Equal XOR | C++ | basically comes down to find all subarrays for which XOR is 0. |
1443 | Minimum Time To Collect All Apples In A Tree | Python | a tree that has apples on some nodes, min number of moves to collect all of them. dfs. |
1444 | Number Of Ways Of Cutting A Pizza | C++ | cut pizza into k slices so that each has at least one apple. dp |
1462 | Course Schedule IV | Python | queries about dependencies in graph. dfs or topological sort. grafy |
1488 | Avoid Flood In The City | C++ | info in solution file |
1509 | Minimum Difference Between Largest And Smallest Value In Three Moves | C++ | in array in 3 moves minimize diff between max and min value |
1514 | Path with Maximum Probability | C++ | Dijkstra's algorithm |
1528 | Shuffle String | C++ | shuffle string according to the mapping given |
1530 | Number Of Good Leaf Nodes Pairs | C++ | count leaves pairs with shortest path smaller than k. bfs. try also dfs |
1559 | Detect Cycles In 2D Grid | C++ Python | as title. graph problem. dfs or bfs. grafy |
1567 | Maximum Length Of Subarray With Positive Product | C++ | as title. dp |
1579 | Remove Max Number Of Edges To Keep Graph Fully Traversable | Python | some edges usable by A, some by B, some by both. max number of edges we can remove so A and B can still traverse the graph. greedy with union find. grafy |
1584 | Min Cost To Connect All Points | Python | minimum spanning tree |
1642 | Furthest Building You Can Reach | C++ | jump between buildings using ladder and bricks. heap. |
1643 | Kth Smallest Instructions | C++ Python | combinations with duplicates |
1685 | Sum Of Absolute Differences In A Sorted Array | Python | for each element in array find sum of abs differences, use formula to do it in O(N) |
1694 | Reformat Phone Number | Python | at title. regex or loops |
1705 | Maximum Number Of Eaten Apples | C++ | each day apples grow and rot, how many can we eat, heap |
1711 | Count Good Meals | C++ | in array find all pairs that sum up to any power of 2. hash map |
1726 | Tuple With Same Product | C++ | array of distinct positive ints, find all tuples a,b,c,d such that ab=cd |
1739 | Building Boxes | Python | stack boxes according to rules. find minimum number of boxes on the floor. matma |
1751 | Maximum Number Of Events That Can Be Attended II | C++ Python | each event has start, end and value. pick at most k events to maximize sum of values. dp and bs. good practise. |
1775 | Equal Sum Arrays With Minimum Number Of Operations | C++ Python | modify values in arrays to make sums equal. greedy approach. |
1781 | Sum Of Beauty Of All Substrings | C++ | beauty of string is diff in freq between most and last frequent chars, sum beauties of all substrings, hashing |
1793 | Maximum Score Of A Good Subarray | C++ Python | a tricky to prove greedy solution, also solution for LC 84 Largest Rectangle in Histogram works here |
1797 | Design Authentication Manager | C++ | use hashmap and set |
1814 | Count Nice Pairs In An Array | C++ Python | transform formula and then use hashing |
1871 | Jump Game VII | C++ | jump on stones if jump length between min and max. bfs |
1884 | Egg Drop With 2 Eggs And N Floors | C++ Python | as title |
1937 | Maximum Number Of Points With Cost | C++ | dp |
1942 | The Number Of The Smallest Unoccupied Chair | C++ | numbered chairs taken/freed by arriving/leaving guests. What chair will be taken by a concrete guest. sort times. use hash map and heap. |
1986 | Minimum Number Of Work Sessions To Finish The Tasks | C++ | distribute tasks into min number of sessions. dfs + memo. try also bitmap |
2002 | Maximum Product Of The Length Of Two Palindromic Subsequences | C++ | as title. dfs, try also other methods |
2054 | Two Best Non Overlapping Events | Python | each event has begin, end and value. sort + bs |
2080 | Range Frequency Queries | C++ | query[l,r,v] to see how many files value v appears in the array between indexes l and r. binary search. |
2096 | Step By Step Directions From A Binary Tree Node To Another | Python | use lowest common ancestor solution |
2104 | Sum Of Subarray Ranges | Python | almost same as Sum Of Subarray Minimums, one pass for min and one for max |
2134 | Minimum Swaps To Group All 1s Together II | Python | Given a binary circular array nums, return the minimum number of swaps required to group all 1s present in the array together at any location. Sliding window. |
2135 | Count Words Obtained After Adding A Letter | C++ | add char and reshuffle to see if can arrive at other string, bitmask + hash map, try also sort and trie, string play |
2145 | Count The Hidden Sequences | Python | given array of diffs between consecutive elements in a hidden array. Also given max and min element that can be in the hidden array. Find number of possible hidden arrays. matma |
2163 | Minimum Difference In Sums After Removal Of Elements | C++ | array has 3 * n ints, remove n elements to minimize left - right, left is sum of first n elements after removal, right is sum of last n. heap |
2178 | Maximum Split Of Positive Even Integers | Python | Split a given int into a sum of a maximum number of unique positive even integers. greedy. |
2182 | Construct String With Repeat Limit | C++ | given string s, reuse its chars and construct a new one lexicographically biggest. Limit on number of repetitions. |
2195 | Append K Integers With Minimal Sum | C++ | given int array nums and an int k. Append k unique positive ints that do not appear in nums so that the resulting total sum is minimum. sort and Gauss formula. |
2203 | Minimum Weighted Subgraph With The Required Paths | C++ | directed graph, nodes src1 src2 dest given, find minimum weight of a subgraph in which it's possible to reach dest from both src1 and src2, Dijkstra. grafy |
2272 | Substring With Largest Variance | C++ | as title. for each pair of chars run modified Kanane algo for finding subarray with largest sum |
2275 | Largest Combination With Bitwise AND Greater Than Zero | C++ | Given int array arr return size of largest combination of vals with a bitwise AND greater than 0. Iterate over 32 bits and nested loop over array |
2312 | Selling Pieces Of Wood | Python | divide a piece of wood into pieces (only certain sizes possible) to be sold. What's the optimal division. dp |
2316 | Count Unreachable Pairs Of Nodes In An Undirected Graph | Python | as title. dfs or union find. grafy |
2349 | Design A Number Container System | C++ | design data structure that maps index to number, function find should return the smallest index for given number. two hash maps |
2360 | Longest Cycle In A Graph | C++ | directed graph given, each node has at most one outgoing edge. find longest cycle. dfs. grafy |
2364 | Count Number Of Bad Pairs | Python | transform formula and then use hashing |
2366 | Minimum Replacements To Sort The Array | Python | matma |
2375 | Construct Smallest Number From DI String | Python | string with chars D (decrease) and I (increase) given. using digits construct smallest number. kind of greedy or backtracking |
2376 | Count Special Integers | Python | int is special if all its digits are distinct. count all special ints smaller than given n. combinatorics. matma |
2381 | Shifting Letters II | Python | line sweep algo |
2434 | Using A Robot To Print The Lexicographically Smallest String | Python | strings manipulations, greedy |
2435 | Paths In Matrix Whose Sum Is Divisible By K | C++ | as title. dp |
2439 | Minimize Maximum Of Array | C++ Python | matma |
2448 | Minimum Cost To Make Array Equal | Python | as title. prefix sum. |
2467 | Most Profitable Path In A Tree | Python | bfs dfs good practise |
2470 | Number Of Subarrays With LCM Equal To K | C++ | least common multiple. use library function to solve. for greatest common divisor similar solution |
2508 | Add Edges To Make Degrees Of All Nodes Even | Python | can add max two edges so that every node in the graph has even degree. grafy |
2513 | Minimize The Maximum Of Two Arrays | C++ | fill arrays with values omitting ones that are divisible by certain ints. lcm, bs, matma |
2542 | Maximum Subsequence Score | C++ | two arrays of same size, pick subsequence of indexes of length k to maximize sum from nums1 multiplied by min from nums2. sort and heap |
2543 | Check If Point Is Reachable | Python | starting at 2d point, some transformations allowed. can we reach destination. greedy or maths. matma. |
2565 | Subsequence With The Minimum Score | C++ | remove chars from t so that it becomes a subsequence of s. dp |
2608 | Shortest Cycle In A Graph | Python | as title. dfs. grafy. |
2659 | Make Array Empty | Python | rotate to move smallest el to front then remove it. keep doing that. number of operations. sort. |
2685 | Count The Number Of Complete Components | C++ | as title. count edges and nodes. grafy |
2712 | Minimum Cost To Make All Characters Equal | Python | binary string. flip values. dp. good practise. |
2799 | Count Complete Subarrays In An Array | C++ | count subarrays that have same number of distinct elements as whole array. sliding window |
2856 | Minimum Array Length After Pair Removals | C++ | sorted array, keep cancelling elements, how many left. tricky intuition. matma |
2919 | Minimum Increment Operations To Make Array Beautiful | Python | given array and k. do increments till all subarrays of length 3 have at least one element k. dp. try also other methods |
2957 | Remove Adjacent Almost Equal Characters | C++ | in a move we can pick index and modify char in string. minimum moves to arrive at string in which there's no adjacent chars that are same of diff by 1. greedy |
no number | Candy Crush 1D | C++ | candy crush in 1D, blmbrg interview |