- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
@ -45,57 +45,3 @@ When you are given two arrays to process, it is common to have one index per arr
- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)
- [3Sum](https://leetcode.com/problems/3sum/)
- [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
## More questions
### Easy
- Implement a circular buffer using an array. ([Solution](https://www.geeksforgeeks.org/circular-queue-set-1-introduction-array-implementation/))
- Given an array of integers, print out a histogram using the said array; include a base layer (all stars) ([Solution](https://www.geeksforgeeks.org/program-make-histogram-array/))
- Given an array and an index, find the product of the elements of the array except the element at that index. ([Solution](https://www.geeksforgeeks.org/a-product-array-puzzle/))
- Given 2 separate arrays, write a method to find the values that exist in both arrays and return them. ([Solution](https://www.geeksforgeeks.org/union-and-intersection-of-two-sorted-arrays-2/))
- Given an input array and another array that describes a new index for each element, mutate the input array so that each element ends up in their new index ([Solution](https://www.geeksforgeeks.org/reorder-a-array-according-to-given-indexes/))
- Discuss the runtime of the algorithm and how you can be sure there would not be any infinite loops
- Given an array of non-negative numbers, find continuous subarray with sum to S. ([Solution 1](https://www.geeksforgeeks.org/find-subarray-with-given-sum/)) ([Solution 2](http://blog.gainlo.co/index.php/2016/06/01/subarray-with-given-sum/))
- Given an array of numbers list out all triplets that sum to 0. Do so with a running time of less than O(n^3). ([Solution 1](https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/)) ([Solution 2](http://blog.gainlo.co/index.php/2016/07/19/3sum/))
- Given an array of numbers list out all quadruplets that sum to 0. Do so with a running time of less than O(n^4). ([Solution](https://www.geeksforgeeks.org/find-four-numbers-with-sum-equal-to-given-sum/))
- Given an array of integers, find the subarray with the largest sum. ([Solution](https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/))
- Find the second maximum value in an array. ([Solution](https://www.geeksforgeeks.org/find-second-largest-element-array/))
- Rotate an array by an offset of k. ([Solution](https://www.geeksforgeeks.org/array-rotation/))
- Remove duplicates in an unsorted array where the duplicates are at a distance of k or less from each other. ([Solution](https://www.geeksforgeeks.org/check-given-array-contains-duplicate-elements-within-k-distance/))
- Given an unsorted list of integers, return true if the list contains any duplicates within k indices of each element. Do it faster than O(n^2). ([Solution](https://www.geeksforgeeks.org/check-given-array-contains-duplicate-elements-within-k-distance/))
- Given an unsorted list of integers, return true if the list contains any fuzzy duplicates within k indices of each element. A fuzzy duplicate is another integer within d of the original integer. Do it faster than O(n^2).
- E.g. If d = 4, then 6 is a fuzzy duplicate of 3 but 8 is not.
- Say you have an unordered list of numbers ranging from 1 to n, and one of the numbers is removed, how do you find that number? What if two numbers are removed? ([Solution](https://www.geeksforgeeks.org/find-the-missing-number/))
- Given an array of string, find the duplicated elements. ([Solution 1](https://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/)) ([Solution 2](http://blog.gainlo.co/index.php/2016/05/10/duplicate-elements-of-an-array/))
- Given an array of integers, find a maximum sum of non-adjacent elements. ([Solution 1](https://www.geeksforgeeks.org/maximum-sum-such-that-no-two-elements-are-adjacent/)) ([Solution 2](http://blog.gainlo.co/index.php/2016/12/02/uber-interview-question-maximum-sum-non-adjacent-elements/))
- E.g. `[1, 0, 3, 9, 2]` should return `10 (1 + 9)`.
- Given an array of integers, modify the array by moving all the zeroes to the end (right side). The order of other elements doesn't matter. ([Solution 1](https://www.geeksforgeeks.org/move-zeroes-end-array/)) ([Solution 2](http://blog.gainlo.co/index.php/2016/11/18/uber-interview-question-move-zeroes/))
- E.g. `[1, 2, 0, 3, 0, 1, 2]`, the program can output `[1, 2, 3, 1, 2, 0, 0]`.
- Given an array, return the length of the longest increasing contiguous subarray. ([Solution 1](https://www.geeksforgeeks.org/longest-increasing-subarray/)) ([Solution 2](http://blog.gainlo.co/index.php/2017/02/02/uber-interview-questions-longest-increasing-subarray/))
- E.g., `[1, 3, 2, 3, 4, 8, 7, 9]`, should return `4` because the longest increasing array is `[2, 3, 4, 8]`
- Given an array of integers where every value appears twice except one, find the single, non-repeating value. Follow up: do so with O(1) space. ([Solution](https://www.geeksforgeeks.org/find-element-appears-array-every-element-appears-twice/))
- E.g., `[2, 5, 3, 2, 1, 3, 4, 5, 1]` returns 4, because it is the only value that appears in the array only once.
### Medium
- Given a list of item prices, find all possible combinations of items that sum a particular value `K`. ([Solution](https://www.geeksforgeeks.org/combinational-sum/))
- Given an array of integers find whether there is a sub-sequence that sums to 0 and return it. ([Solution](https://www.geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/))
- E.g. `[1, 2, -3, 1]` => `[1, 2, -3]` or `[2, -3, 1]`
- Trapping rain water: You have an array with the heights of an island (at point 1, point 2 etc) and you want to know how much water would remain on this island (without flowing away). ([Solution](https://www.geeksforgeeks.org/trapping-rain-water/))
### Hard
- Given a set of rectangles represented by a height and an interval along the y-axis, determine the size of its union. ([Solution](https://www.geeksforgeeks.org/divide-and-conquer-set-7-the-skyline-problem/))
- Given an array, find the longest arithmetic progression. ([Solution](https://www.geeksforgeeks.org/longest-arithmetic-progression-dp-35/))
- Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
- E.g. `[100, 4, 200, 1, 3, 2] => 4`. Explanation: The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. Note: Your algorithm should run in O(n) complexity. ([Solution](https://www.geeksforgeeks.org/longest-consecutive-subsequence/))
### Other
- In an array of arrays, e.g. given `[[], [1, 2, 3], [4, 5], [], [], [6, 7], [8], [9, 10], [], []]`, print: `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`.
- Implement an iterator that supports `hasNext()`, `next()` and `remove()` methods.
- Paginate an array with constraints, such as skipping certain items.
- Given array of arrays, sort them in ascending order.
- Given an array containing only digits `0-9`, add one to the number and return the array.
- E.g. Given `[1, 4, 2, 1]` which represents `1421`, return `[1, 4, 2, 2]` which represents `1422`.
- Given a flight itinerary consisting of starting city, destination city, and ticket price (2D list) - find the optimal price flight path to get from start to destination. (A variation of Dynamic Programming Shortest Path)
- Given some coin denominations and a target value `M`, return the coins combination with the minimum number of coins.
- Time complexity: `O(MN)`, where N is the number of distinct type of coins.
- Space complexity: `O(M)`.
- Given a set of numbers in an array which represent a number of consecutive days of Airbnb reservation requested, as a host, pick the sequence which maximizes the number of days of occupancy, at the same time, leaving at least a 1-day gap in-between bookings for cleaning.
- The problem reduces to finding the maximum sum of non-consecutive array elements.
- E.g.
```
// [5, 1, 1, 5] => 10
The above array would represent an example booking period as follows -
// Dec 1 - 5
// Dec 5 - 6
// Dec 6 - 7
// Dec 7 - 12
The answer would be to pick Dec 1-5 (5 days) and then pick Dec 7-12 for a total of 10 days of
occupancy, at the same time, leaving at least 1-day gap for cleaning between reservations.
Similarly,
// [3, 6, 4] => 7
// [4, 10, 3, 1, 5] => 15
```
- Given a list of denominations (e.g., `[1, 2, 5]` means you have coins worth $1, $2, and \$5) and a target number `k`, find all possible combinations, if any, of coins in the given denominations that add up to `k`. You can use coins of the same denomination more than once.
- You are climbing a flight of stairs. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? E.g. Input: 3, Output: 3. Explanation: `[1, 1, 1], [1, 2], [2, 1]`.
In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When traversing the matrix, always ensure that your current position is within the boundary of the matrix and has not been visited before.
In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When traversing the matrix, always ensure that your current position is within the boundary of the matrix and has not been visited before.
A simple template for doing depth-first searches on a matrix goes like this:
@ -101,23 +101,13 @@ For additional tips on BFS and DFS, you can refer to this [LeetCode post](https:
- [Graph Valid Tree (Leetcode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (Leetcode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
## More questions
- Given a list of sorted words from an alien dictionary, find the order of the alphabet.
- Alien Dictionary Topological Sort question.
- Find if a given string matches any path in a labeled graph. A path may contain cycles.
- Given a bipartite graph, separate the vertices into two sets.
- You are a thief trying to sneak across a rectangular 100 x 100m field. There are alarms placed on the fields and they each have a circular sensing radius which will trigger if anyone steps into it. Each alarm has its own radius. Determine if you can get from one end of the field to the other end.
- Given a graph and two nodes, determine if there exists a path between them.
- [Graph Valid Tree (LeetCode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (LeetCode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
@ -13,13 +13,8 @@ If you see a top or lowest _k_ being mentioned in the question, it is usually a
If you require the top _k_ elements use a Min Heap of size _k_. Iterate through each element, pushing it into the heap. Whenever the heap size exceeds _k_, remove the minimum element, that will guarantee that you have the _k_ largest elements.
## Recommended Leetcode questions
## Recommended LeetCode questions
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)
- [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)
## More questions
- Merge `K` sorted lists together into a single list.
- Given a stream of integers, write an efficient function that returns the median value of the integers.
- [Meeting Rooms (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms/) and [Meeting Rooms II (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms-ii/)
## More questions
- Given a list of schedules, provide a list of times that are available for a meeting.
```
[
[[4,5], [6,10], [12,14]],
[[4,5], [5,9], [13,16]],
[[11,14]]
]
Example Output:
[[0,4], [11,12], [16,23]]
```
- You have a number of meetings (with their start and end times). You need to schedule them using the minimum number of rooms. Return the list of meetings in every room.
- Interval ranges:
- Given 2 interval ranges, create a function to tell me if these ranges intersect. Both start and end are inclusive: `[start, end]`
- E.g. `[1, 4]` and `[5, 6]` => `false`
- E.g. `[1, 4]` and `[3, 6]` => `true`
- Given 2 interval ranges that intersect, now create a function to merge the 2 ranges into a single continuous range.
- E.g. `[1, 4]` and `[3, 6]` => `[1, 6]`
- Now create a function that takes a group of unsorted, unorganized intervals, merge any intervals that intersect and sort them. The result should be a group of sorted, non-intersecting intervals.
- Now create a function to merge a new interval into a group of sorted, non-intersecting intervals. After the merge, all intervals should remain non-intersecting.
- Given a list of meeting times, check if any of them overlap. The follow-up question is to return the minimum number of rooms required to accommodate all the meetings.
- Given a linked list, in addition to the next pointer, each node has a child pointer that can point to a separate list. With the head node, flatten the list to a single-level linked list.
- Reverse a singly linked list. Implement it recursively and iteratively.
- Convert a binary tree to a doubly circular linked list.
- Implement an LRU cache with O(1) runtime for all its operations.
- Check distance between values in linked list.
- A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
- Given a singly linked list (a list which can only be traversed in one direction), find the item that is located at 'k' items from the end. So if the list is a, b, c, d and k is 2 then the answer is 'c'. The solution should not search the list twice.
- How can you tell if a Linked List is a Palindrome?
- [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)
## More questions
- Create a square root function.
- Given a string such as "123" or "67", write a function to output the number represented by the string without using casting.
- Make a program that can print out the text form of numbers from 1 - 1000 (ex. 20 is "twenty", 105 is "one hundred and five").
- Write a function that parses Roman numerals.
- E.g. `XIV` returns `14`.
- Write in words for a given digit.
- E.g. `123` returns `one hundred and twenty three`.
- Given a number `N`, find the largest number just smaller than `N` that can be formed using the same digits as `N`.
- Compute the square root of `N` without using any existing functions.
- Given numbers represented as binary strings, and return the string containing their sum.
- E.g. `add('10010', '101')` returns `'10111'`.
- Take in an integer and return its english word-format.
- E.g. 1 -> "one", -10,203 -> "negative ten thousand two hundred and three".
- Write a function that returns values randomly, according to their weight. Suppose we have 3 elements with their weights: A (1), B (1) and C (2). The function should return A with probability 25%, B with 25% and C with 50% based on the weights.
- You're given a 3 x 3 board of a tile puzzle, with 8 tiles numbered 1 to 8, and an empty spot. You can move any tile adjacent to the empty spot, to the empty spot, creating an empty spot where the tile originally was. The goal is to find a series of moves that will solve the board, i.e. get `[[1, 2, 3], [4, 5, 6], [7, 8, - ]]` where - is the empty tile.
- Boggle implementation. Given a dictionary, and a matrix of letters, find all the words in the matrix that are in the dictionary. You can go across, down or diagonally.
- The values of the matrix will represent numbers of carrots available to the rabbit in each square of the garden. If the garden does not have an exact center, the rabbit should start in the square closest to the center with the highest carrot count. On a given turn, the rabbit will eat the carrots available on the square that it is on, and then move up, down, left, or right, choosing the square that has the most carrots. If there are no carrots left on any of the adjacent squares, the rabbit will go to sleep. You may assume that the rabbit will never have to choose between two squares with the same number of carrots. Write a function which takes a garden matrix and returns the number of carrots the rabbit eats. You may assume the matrix is rectangular with at least 1 row and 1 column, and that it is populated with non-negative integers. For example,
- In the Game of life, calculate how to compute the next state of the board. Follow up was to do it if there were memory constraints (board represented by a 1 TB file).
- Grid Illumination: Given an NxN grid with an array of lamp coordinates. Each lamp provides illumination to every square on their x axis, every square on their y axis, and every square that lies in their diagonal (think of a Queen in chess). Given an array of query coordinates, determine whether that point is illuminated or not. The catch is when checking a query all lamps adjacent to, or on, that query get turned off. The ranges for the variables/arrays were about: 10^3 <N<10^9,10^3<lamps<10^9,10^3<queries<10^9.
- You are given a matrix of integers. Modify the matrix such that if a row or column contains a 0, make the values in the entire row or column 0.
- Given an N x N matrix filled randomly with different colors (no limit on what the colors are), find the total number of groups of each color - a group consists of adjacent cells of the same color touching each other.
- You have a 4 x 4 board with characters. You need to write a function that finds if a certain word exists in the board. You can only jump to neighboring characters (including diagonally adjacent).
- Count the number of islands in a binary matrix of 0's and 1's.
- Check a 6 x 7 Connect 4 board for a winning condition.
- Given a fully-filled Sudoku board, check whether fulfills the Sudoku condition.
- Implement a function that checks if a player has won tic-tac-toe.
- Given an N x N matrix of 1's and 0's, figure out if all of the 1's are connected.
- You are given a 7 digit phone number, and you should find all possible letter combinations based on the digit-to-letter mapping on numeric pad and return only the ones that have valid match against a given dictionary of words.
- Give all possible letter combinations from a phone number.
- Implement a Queue class from scratch with an existing bug, the bug is that it cannot take more than 5 elements.
- Implement a Queue using two stacks. You may only use the standard `push()`, `pop()`, and `peek()` operations traditionally available to stacks. You do not need to implement the stack yourself (i.e. an array can be used to simulate a stack).
@ -11,7 +11,7 @@ Remember to always define a base case so that your recursion will end.
Recursion implicitly uses a stack. Hence all recursive approaches can be rewritten iteratively using a stack. Beware of cases where the recursion level goes too deep and causes a stack overflow (the default limit in Python is 1000). You may get bonus points for pointing this out to the interviewer. Recursion will never be O(1) space complexity because a stack is involved, unless there is [tail-call optimization](https://stackoverflow.com/questions/310974/what-is-tail-call-optimization) (TCO). Find out if your chosen language supports TCO.
## Recommended Leetcode questions
## Recommended LeetCode questions
- [Subsets](https://leetcode.com/problems/subsets/) and [Subsets II](https://leetcode.com/problems/subsets-ii/)
- [Strobogrammatic Number II (Leetcode Premium)](https://leetcode.com/problems/strobogrammatic-number-ii/)
- [Strobogrammatic Number II (LeetCode Premium)](https://leetcode.com/problems/strobogrammatic-number-ii/)
- [Encode and Decode Strings (Leetcode Premium)](https://leetcode.com/problems/encode-and-decode-strings/)
## More questions
- Output list of strings representing a page of hostings given a list of CSV strings.
- Given a list of words, find the word pairs that when concatenated form a palindrome.
- Find the most efficient way to identify what character is out of place in a non-palindrome.
- Implement a simple regex parser which, given a string and a pattern, returns a boolean indicating whether the input matches the pattern. By simple, we mean that the regex can only contain the following special characters: `*` (star), `.` (dot), `+` (plus). The star means that there will be zero or more of the previous character in that place in the pattern. The dot means any character for that position. The plus means one or more of previous character in that place in the pattern.
- Find all words from a dictionary that are x edit distance away.
- Given a string IP and number n, print all CIDR addresses that cover that range.
- Write a function called `eval`, which takes a string and returns a boolean. This string is allowed 6 different characters: `0`, `1`, `&`, `|`, `(`, and `)`. `eval` should evaluate the string as a boolean expression, where `0` is `false`, `1` is `true`, `&` is an `and`, and `|` is an `or`.
- E.g `"(0 | (1 | 0)) & (1 & ((1 | 0) & 0))"`
- Given a pattern string like `"abba"` and an input string like `"redbluebluered"`, return `true` if and only if there's a one to one mapping of letters in the pattern to substrings of the input.
- E.g. `"abba"` and `"redbluebluered"` should return `true`.
- E.g. `"aaaa"` and `"asdasdasdasd"` should return `true`.
- E.g. `"aabb"` and `"xyzabcxzyabc"` should return `false`.
- If you received a file in chunks, calculate when you have the full file. Quite an open-ended question. Can assume chunks come with start and end, or size, etc.
- Given a list of names (strings) and the width of a line, design an algorithm to display them using the minimum number of lines.
- Given a string, return the string with duplicate characters removed.
- Write a function that receives a regular expression (allowed chars = from `'a'` to `'z'`, `'*'`, `'.'`) and a string containing lower case english alphabet characters and return `true` or `false` whether the string matches the regex.
- E.g. `'ab*a'`, `'abbbbba'` => `true`.
- E.g. `'ab*b.'`, `'aba'` => `true`.
- E.g. `'abc*'`, `'acccc'` => `false`.
- Given a rectangular grid with letters, search if some word is in the grid.
- Given two strings representing integer numbers (`'123'` , `'30'`) return a string representing the sum of the two numbers: `'153'`.
- A professor wants to see if two students have cheated when writing a paper. Design a function `hasCheated(String s1, String s2, int N)` that evaluates to `true` if two strings have a common substring of length `N`.
- Follow up: Assume you don't have the possibility of using `String.contains()` and `String.substring()`. How would you implement this?
- Print all permutations of a given string.
- Parse a string containing numbers and `'+'`, `'-'` and parentheses. Evaluate the expression. `-2+(3-5)` should return `-4`.
- Output a substring with at most `K` unique characters.
- E.g. `'aabc'` and `k` = 2 => `'aab'`.
- Ensure that there are a minimum of `N` dashes between any two of the same characters of a string.
- E.g. `n = 2, string = 'ab-bcdecca'` => `'ab--bcdec--ca'`.
- Find the longest palindrome in a string.
- Give the count and the number following in the series.
- E.g. `1122344`, next: `21221324`, next: `12112211121214`.
- Count and say problem.
- Compress a string by grouping consecutive similar questions together:
- E.g. `'aaabbbcc' =>`'a3b3c2'`.
- You have a string consisting of open and closed parentheses, but parentheses may be imbalanced. Make the parentheses balanced and return the new string.
- Given a set of strings, return the smallest subset that contains prefixes for every string.
- E.g. `['foo', 'foog', 'food', 'asdf']` => `['foo', 'asdf']`.
- Write a function that would return all the possible words generated when using a phone (pre-smartphone era) numpad to type.
- Given a dictionary and a word, find the minimum number of deletions needed on the word in order to make it a valid word.
- Find the lowest common ancestor of two nodes in a binary search tree.
- Print the nodes in an n-ary tree level by level, one printed line per level.
- Given a directory of files and folders (and relevant functions), how would you parse through it to find equivalent files?
- Write a basic file system and implement the commands ls, pwd, mkdir, create, rm, cd, cat, mv.
- Compute the intersection of two binary search trees.
- Given a binary tree, output all the node to leaf paths of it.
- Given a string of characters without spaces, is there a way to break the string into valid words without leftover characters?
- Print a binary tree level by level.
- Determine if a binary tree is "complete" (i.e, if all leaf nodes were either at the maximum depth or max depth-1, and were 'pressed' along the left side of the tree).
- Find the longest path in a binary tree. The path may start and end at any node.
- Determine if a binary tree is a BST.
- Given a binary tree, serialize it into a string. Then deserialize it.
- Print a binary tree by column.
- Given a node, find the next element in a BST.
- Find the shortest subtree that consist of all the deepest nodes. The tree is not binary.
- Print out the sum of each row in a binary tree.
- Pretty print a JSON object.
- Convert a binary tree to a doubly circular linked list.
- Find the second largest number in a binary tree.
- Given a tree, find the longest branch.
- Convert a tree to a linked list.
- Given two trees, write code to find out if tree A is a subtree of tree B.
- [Graph Valid Tree (Leetcode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (Leetcode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
- [Graph Valid Tree (LeetCode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (LeetCode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)