Staple - 1
Staple - 1
Leetcode Offline Explanation: there are four ways to make up the amount:
5=5
------------------------------ 5=2+2+1
Single Element in a Sorted Array 5=2+1+1+1
------------------------------ 5=1+1+1+1+1
Input: [1,1,2,3,3,4,4,8,8]
Output: 2 Example 3:
------------------------------ Example:
------------------------------ Input: 2
Coin Change 2 Output: 987
------------------------------ Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Note: ------------------------------
You can assume that ------------------------------
Find All Duplicates in an Array
0 <= amount <= 5000 ------------------------------
1 <= coin <= 5000 Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array),
the number of coins is less than 500 some elements appear twice and others appear once.
the answer is guaranteed to fit into signed 32-bit integer
Find all the elements that appear twice in this array.
Given "pwwkew", the answer is "wke", with the length of 3. Note that ------------------------------
------------------------------
ZigZag Conversion Note:
------------------------------ The input is assumed to be a 32-bit signed integer. Your function
should return 0 when the reversed integer overflows.
The string "PAYPALISHIRING" is written in a zigzag pattern on a
given number of rows like this: (you may want to display this ------------------------------
pattern in a fixed font for better legibility) ------------------------------
String to Integer (atoi)
P A H N ------------------------------
A P L S I I G Implement atoi to convert a string to an integer.
Y I R
Hint: Carefully consider all possible input cases. If you want a
challenge, please do not see below and ask yourself what are the
And then read line by line: "PAHNAPLSIIGYIR" possible input cases.
Write the code that will take a string and make this conversion Notes:
given a number of rows: It is intended for this problem to be specified vaguely (ie, no
given input specs). You are responsible to gather all the input
string convert(string text, int nRows); requirements up front.
Here are some good questions to ask before coding. Bonus points for The string can contain additional characters after those that form
you if you have already thought through this! the integral number, which are ignored and have no effect on the
behavior of this function.
If the integer's last digit is 0, what should the output be? ie,
cases such as 10, 100. If the first sequence of non-whitespace characters in str is not a
valid integral number, or if no such sequence exists because either
Did you notice that the reversed integer might overflow? Assume the str is empty or it contains only whitespace characters, no
input is a 32-bit integer, then the reverse of 1000000003 overflows. conversion is performed.
How should you handle such cases?
If no valid conversion could be performed, a zero value is returned.
For the purpose of this problem, assume that your function returns 0 If the correct value is out of the range of representable values,
when the reversed integer overflows. INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
------------------------------
------------------------------
Palindrome Number
------------------------------ Note: You may not slant the container and n is at least 2.
Determine whether an integer is a palindrome. Do this without extra
space. ------------------------------
------------------------------
click to show spoilers. Integer to Roman
------------------------------
Some hints: Given an integer, convert it to a roman numeral.
The function prototype should be: Note: The solution set must not contain duplicate triplets.
bool isMatch(const char *s, const char *p)
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). For example,
------------------------------
------------------------------ Given linked list: 1->2->3->4->5, and n = 2.
Letter Combinations of a Phone Number
------------------------------ After removing the second node from the end, the linked list
Given a digit string, return all possible letter combinations that becomes 1->2->3->5.
the number could represent.
Note:
A mapping of digit to letters (just like on the telephone buttons) Given n will always be valid.
is given below. Try to do this in one pass.
------------------------------
------------------------------
Input:Digit string "23" Valid Parentheses
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. ------------------------------
Given a string containing just the characters '(', ')', '{', '}',
'[' and ']', determine if the input string is valid.
Note: The brackets must close in the correct order, "()" and "()[]{}" are
Although the above answer is in lexicographical order, your answer all valid but "(]" and "([)]" are not.
could be in any order you want.
------------------------------
------------------------------ ------------------------------
------------------------------ Merge Two Sorted Lists
4Sum ------------------------------
------------------------------ Merge two sorted linked lists and return it as a new list. The new
Given an array S of n integers, are there elements a, b, c, and d in list should be made by splicing together the nodes of the first two
S such that a + b + c + d = target? Find all unique quadruplets in lists.
the array which gives the sum of target. ------------------------------
------------------------------
Note: The solution set must not contain duplicate quadruplets. Generate Parentheses
------------------------------
------------------------------
------------------------------ For k = 3, you should return: 3->2->1->4->5
Merge k Sorted Lists
------------------------------ ------------------------------
------------------------------
Merge k sorted linked lists and return it as one sorted list. Remove Duplicates from Sorted Array
Analyze and describe its complexity. ------------------------------
------------------------------ Given a sorted array, remove the duplicates in place such that each
------------------------------ element appear only once and return the new length.
Swap Nodes in Pairs
------------------------------
Do not allocate extra space for another array, you must do this in
Given a linked list, swap every two adjacent nodes and return its place with constant memory.
head.
For example,
For example, Given input array nums = [1,1,2],
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your function should return length = 2, with the first two elements
of nums being 1 and 2 respectively. It doesn't matter what you leave
Your algorithm should use only constant space. You may not modify beyond the new length.
the values in the list, only nodes itself can be changed.
------------------------------
------------------------------ ------------------------------
------------------------------ Remove Element
Reverse Nodes in k-Group ------------------------------
------------------------------ Given an array and a value, remove all instances of that value in
place and return the new length.
Given a linked list, reverse the nodes of a linked list k at a time
and return its modified list.
Do not allocate extra space for another array, you must do this in
place with constant memory.
k is a positive integer and is less than or equal to the length of The order of elements can be changed. It doesn't matter what you
the linked list. If the number of nodes is not a multiple of k then leave beyond the new length.
left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be Example:
changed. Given input array nums = [3,2,2,3], val = 3
------------------------------
------------------------------
Implement strStr() The replacement must be in-place, do not allocate extra memory.
------------------------------
Implement strStr(). Here are some examples. Inputs are in the left-hand column and its
corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
Returns the index of the first occurrence of needle in haystack, or 3,2,1 → 1,2,3
-1 if needle is not part of haystack. 1,1,5 → 1,5,1
------------------------------ ------------------------------
------------------------------ ------------------------------
Divide Two Integers Longest Valid Parentheses
------------------------------ ------------------------------
Given a string containing just the characters '(' and ')', find the
Divide two integers without using multiplication, division and mod length of the longest valid (well-formed) parentheses substring.
operator.
------------------------------
------------------------------ Another example is ")()())", where the longest valid parentheses
Substring with Concatenation of All Words substring is "()()", which has length = 4.
------------------------------
------------------------------
You are given a string, s, and a list of words, words, that are all ------------------------------
of the same length. Find all starting indices of substring(s) in s Search in Rotated Sorted Array
that is a concatenation of each word in words exactly once and ------------------------------
without any intervening characters. Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.
The Sudoku board could be partially filled, where empty cells are ------------------------------
filled with the character '.'. ------------------------------
Combination Sum
------------------------------
A partially filled sudoku which is valid. Given a set of candidate numbers (C) (without duplicates) and a
target number (T), find all unique combinations in C where the
candidate numbers sums to T.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable.
Only the filled cells need to be validated. The same repeated number may be chosen from C unlimited number of
times.
------------------------------
------------------------------
Sudoku Solver Note:
------------------------------
Write a program to solve a Sudoku puzzle by filling the empty cells. All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
Note:
The above elevation map is represented by array
All numbers (including target) will be positive integers. [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue
The solution set must not contain duplicate combinations. section) are being trapped. Thanks Marcos for contributing this
image!
------------------------------
------------------------------
Multiply Strings
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target ------------------------------
8, Given two non-negative integers num1 and num2 represented as
A solution set is: strings, return the product of num1 and num2.
[ Note:
[1, 7],
[1, 2, 5], The length of both num1 and num2 is < 110.
[2, 6], Both num1 and num2 contains only digits 0-9.
[1, 1, 6] Both num1 and num2 does not contain any leading zero.
] You must not use any built-in BigInteger library or convert the
inputs to integer directly.
------------------------------
------------------------------ ------------------------------
First Missing Positive ------------------------------
------------------------------ Wildcard Matching
------------------------------
Given an unsorted integer array, find the first missing positive Implement wildcard pattern matching with support for '?' and '*'.
integer.
isMatch("aaa","aa") → false ]
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true ------------------------------
isMatch("aab", "c*a*b") → false ------------------------------
Permutations II
------------------------------ ------------------------------
------------------------------
Jump Game II Given a collection of numbers that might contain duplicates, return
------------------------------ all possible unique permutations.
------------------------------
Given an integer n, return all distinct solutions to the n-queens ------------------------------
puzzle. Spiral Matrix
------------------------------
Each solution contains a distinct board configuration of the n- Given a matrix of m x n elements (m rows, n columns), return all
queens' placement, where 'Q' and '.' both indicate a queen and an elements of the matrix in spiral order.
empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle: For example,
Given the following matrix:
[
[".Q..", // Solution 1
"...Q", [
"Q...", [ 1, 2, 3 ],
"..Q."], [ 4, 5, 6 ],
[ 7, 8, 9 ]
["..Q.", // Solution 2 ]
"Q...",
"...Q",
".Q.."] You should return [1,2,3,6,9,8,7,4,5].
]
------------------------------
------------------------------ ------------------------------
------------------------------ Jump Game
N-Queens II ------------------------------
------------------------------
Follow up for N-Queens problem. Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Now, instead outputting board configurations, return the total
number of distinct solutions.
Each element in the array represents your maximum jump length at
that position.
------------------------------
------------------------------
Maximum Subarray Determine if you are able to reach the last index.
------------------------------
------------------------------
------------------------------ ------------------------------
Merge Intervals Spiral Matrix II
------------------------------ ------------------------------
Given a collection of intervals, merge all overlapping intervals. Given an integer n, generate a square matrix filled with elements
from 1 to n2 in spiral order.
For example,
Given [1,3],[2,6],[8,10],[15,18], For example,
return [1,6],[8,10],[15,18]. Given n = 3,
------------------------------
------------------------------ Given n and k, return the kth permutation sequence.
Length of Last Word
------------------------------ Note: Given n will be between 1 and 9 inclusive.
Given a string s consists of upper/lower-case alphabets and empty ------------------------------
space characters ' ', return the length of last word in the string. ------------------------------
Rotate List
If the last word does not exist, return 0. ------------------------------
Given a list, rotate the list to the right by k places, where k is
Note: A word is defined as a character sequence consists of non- non-negative.
space characters only.
For example:
Given 1->2->3->4->5->NULL and k = 2,
For example, return 4->5->1->2->3->NULL.
Given s = "Hello World", ------------------------------
return 5. ------------------------------
Unique Paths
------------------------------ ------------------------------
A robot is located at the top-left corner of a m x n grid (marked
'Start' in the diagram below).
Some examples:
The robot can only move either down or right at any point in time. "0" => true
The robot is trying to reach the bottom-right corner of the grid " 0.1 " => true
(marked 'Finish' in the diagram below). "abc" => false
"1 a" => false
How many possible unique paths are there? "2e10" => true
For example, You may assume the integer do not contain any leading zero, except
There is one obstacle in the middle of a 3x3 grid as illustrated the number 0 itself.
below.
The digits are stored such that the most significant digit is at the
[ head of the list.
[0,0,0], ------------------------------
[0,1,0], ------------------------------
[0,0,0] Add Binary
] ------------------------------
The total number of unique paths is 2. Given two binary strings, return their sum (also a binary string).
------------------------------
Sqrt(x)
------------------------------
You should pack your words in a greedy approach; that is, pack as Implement int sqrt(int x).
many words as you can in each line. Pad extra spaces ' ' when
necessary so that each line has exactly L characters. Compute and return the square root of x.
------------------------------
------------------------------
Climbing Stairs
Extra spaces between words should be distributed as evenly as ------------------------------
possible. If the number of spaces on a line do not divide evenly You are climbing a stair case. It takes n steps to reach to the top.
between words, the empty slots on the left will be assigned more
spaces than the slots on the right. Each time you can either climb 1 or 2 steps. In how many distinct
ways can you climb to the top?
For the last line of text, it should be left justified and no extra Note: Given n will be a positive integer.
space is inserted between words.
------------------------------
------------------------------
Simplify Path
For example, ------------------------------
words: ["This", "is", "an", "example", "of", "text", Given an absolute path for a file (Unix-style), simplify it.
"justification."]
L: 16. For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
A line other than the last line might contain only one word. What Given two words word1 and word2, find the minimum number of steps
should you do in this case? required to convert word1 to word2. (each operation is counted as 1
In this case, that line should be left-justified. step.)
------------------------------
You have the following 3 operations permitted on a word: [23, 30, 34, 50]
]
Follow up:
Note:
Did you use extra space? You are not suppose to use the library's sort function for this
A straight forward solution using O(mn) space is probably a bad problem.
idea.
A simple improvement uses O(m + n) space, but still not the best
solution. click to show follow up.
Could you devise a constant space solution?
Follow up:
------------------------------ A rather straight forward solution is a two-pass algorithm using
------------------------------ counting sort.
Search a 2D Matrix First, iterate the array counting number of 0's, 1's, and 2's, then
------------------------------ overwrite array with total number of 0's, then 1's and followed by
Write an efficient algorithm that searches for a value in an m x n 2's.
matrix. This matrix has the following properties: Could you come up with an one-pass algorithm using only constant
space?
------------------------------ Given a 2D board and a word, find if the word exists in the grid.
------------------------------
Combinations
------------------------------ The word can be constructed from letters of sequentially adjacent
cell, where "adjacent" cells are those horizontally or vertically
Given two integers n and k, return all possible combinations of k neighboring. The same letter cell may not be used more than once.
numbers out of 1 ... n.
[
['A','B','C','E'],
[ ['S','F','C','S'],
[2,4], ['A','D','E','E']
[3,4], ]
[2,3],
[1,2],
[1,3], word = "ABCCED", -> returns true,
[1,4], word = "SEE", -> returns true,
] word = "ABCB", -> returns false.
------------------------------ ------------------------------
------------------------------ ------------------------------
Subsets Remove Duplicates from Sorted Array II
------------------------------ ------------------------------
Given a set of distinct integers, nums, return all possible subsets. Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
Note: The solution set must not contain duplicate subsets.
For example,
For example, Given sorted array nums = [1,1,1,2,2,3],
If nums = [1,2,3], a solution is:
Your function should return length = 5, with the first five elements
of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave
[ beyond the new length.
[3],
[1], ------------------------------
[2], ------------------------------
Search in Rotated Sorted Array II
------------------------------ Above is a histogram where width of each bar is 1, given height =
[2,1,5,6,2,3].
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
For example, if we choose the node "gr" and swap its two children, Given a non-negative integer n representing the total number of bits
it produces a scrambled string "rgeat". in the code, print the sequence of gray code. A gray code sequence
must begin with 0.
rgeat For example, given n = 2, return [0,1,3,2]. Its gray code sequence
/ \ is:
rg eat
/ \ / \ 00 - 0
r g e at 01 - 1
/ \ 11 - 3
a t 10 - 2
Similarly, if we continue to swap the children of nodes "eat" and For example, [0,2,3,1] is also a valid gray code sequence according
"at", it produces a scrambled string "rgtae". to the above definition.
For now, the judge is able to judge based on one instance of gray
rgtae code sequence. Sorry about that.
/ \ ------------------------------
rg tae ------------------------------
/ \ / \ Subsets II
r g ta e ------------------------------
/ \
t a Given a collection of integers that might contain duplicates, nums,
return all possible subsets.
We say that "rgtae" is a scrambled string of "great". Note: The solution set must not contain duplicate subsets.
Given two strings s1 and s2 of the same length, determine if s2 is a For example,
If nums = [1,2,2], a solution is: Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
[
[2],
[1], Note:
[1,2,2], Given m, n satisfy the following condition:
[2,2], 1 ≤ m ≤ n ≤ length of list.
[1,2],
[] ------------------------------
] ------------------------------
Restore IP Addresses
------------------------------ ------------------------------
------------------------------ Given a string containing only digits, restore it by returning all
Decode Ways possible valid IP address combinations.
------------------------------
A message containing letters from A-Z is being encoded to numbers For example:
using the following mapping: Given "25525511135",
For example, 1
Given encoded message "12", \
it could be decoded as "AB" (1 2) or "L" (12). 2
/
3
------------------------------
For example,
Given n = 3, your program should return all 5 unique BST's shown Given a binary tree, determine if it is a valid binary search tree
below. (BST).
1 3 3 2 1
\ / / / \ \ Assume a BST is defined as follows:
3 2 1 1 3 2
/ / \ \ The left subtree of a node contains only nodes with keys less than
2 1 2 3 the node's key.
The right subtree of a node contains only nodes with keys greater
than the node's key.
------------------------------ Both the left and right subtrees must also be binary search trees.
------------------------------
Unique Binary Search Trees
------------------------------
Given n, how many structurally unique BST's (binary search trees) Example 1:
that store values 1...n?
2
/ \
For example, 1 3
Given n = 3, there are a total of 5 unique BST's.
Binary tree [2,1,3], return true.
1 3 3 2 1
\ / / / \ \ Example 2:
3 2 1 1 3 2
/ / \ \ 1
2 1 2 3 / \
2 3
Two binary trees are considered equal if they are structurally return its level order traversal as:
identical and the nodes have the same value.
[
------------------------------ [3],
------------------------------ [9,20],
Symmetric Tree [15,7]
------------------------------ ]
Given a binary tree, check whether it is a mirror of itself (ie,
symmetric around its center).
------------------------------
------------------------------
For example, this binary tree [1,2,2,3,4,4,3] is symmetric: Binary Tree Zigzag Level Order Traversal
------------------------------
1 Given a binary tree, return the zigzag level order traversal of its
/ \ nodes' values. (ie, from left to right, then right to left for the
2 2 next level and alternate between).
/ \ / \
3 4 4 3
For example:
Given binary tree [3,9,20,null,null,15,7],
[
Note: [3],
Bonus points if you could solve it both recursively and iteratively. [20,9],
[15,7]
------------------------------ ]
------------------------------
Binary Tree Level Order Traversal
------------------------------ ------------------------------
Given a binary tree, return the level order traversal of its nodes' ------------------------------
values. (ie, from left to right, level by level). Maximum Depth of Binary Tree
------------------------------
Given a binary tree, find its maximum depth.
For example:
Given binary tree [3,9,20,null,null,15,7], The maximum depth is the number of nodes along the longest path from
the root node down to the farthest leaf node.
3 ------------------------------
/ \ ------------------------------
9 20 Construct Binary Tree from Preorder and Inorder Traversal
/ \ ------------------------------
15 7 Given preorder and inorder traversal of a tree, construct the binary
tree. Given a singly linked list where elements are sorted in ascending
order, convert it to a height balanced BST.
Note: ------------------------------
You may assume that duplicates do not exist in the tree. ------------------------------
Balanced Binary Tree
------------------------------ ------------------------------
------------------------------ Given a binary tree, determine if it is height-balanced.
Construct Binary Tree from Inorder and Postorder Traversal
------------------------------
Given inorder and postorder traversal of a tree, construct the
binary tree. For this problem, a height-balanced binary tree is defined as a
binary tree in which the depth of the two subtrees of every node
Note: never differ by more than 1.
You may assume that duplicates do not exist in the tree.
------------------------------
------------------------------ ------------------------------
------------------------------ Minimum Depth of Binary Tree
Binary Tree Level Order Traversal II ------------------------------
------------------------------ Given a binary tree, find its minimum depth.
Given a binary tree, return the bottom-up level order traversal of
its nodes' values. (ie, from left to right, level by level from leaf The minimum depth is the number of nodes along the shortest path
to root). from the root node down to the nearest leaf node.
------------------------------
------------------------------
For example: Path Sum
Given binary tree [3,9,20,null,null,15,7], ------------------------------
3 Given a binary tree and a sum, determine if the tree has a root-to-
/ \ leaf path such that adding up all the values along the path equals
9 20 the given sum.
/ \
15 7
For example:
Given the below binary tree and sum = 22,
------------------------------
------------------------------ return true, as there exist a root-to-leaf path 5->4->11->2 which
Convert Sorted Array to Binary Search Tree sum is 22.
------------------------------ ------------------------------
Given an array where elements are sorted in ascending order, convert ------------------------------
it to a height balanced BST. Path Sum II
------------------------------ ------------------------------
------------------------------
Convert Sorted List to Binary Search Tree Given a binary tree and a sum, find all root-to-leaf paths where
------------------------------ each path's sum equals the given sum.
\
6
For example:
Given the below binary tree and sum = 22,
click to show hints.
5
/ \ Hints:
4 8 If you notice carefully in the flattened tree, each node's right
/ / \ child points to the next node of a pre-order traversal.
11 13 4
/ \ / \ ------------------------------
7 2 5 1 ------------------------------
Distinct Subsequences
------------------------------
struct TreeLinkNode {
TreeLinkNode *left;
The flattened tree should look like: TreeLinkNode *right;
TreeLinkNode *next;
1 }
\
2
\
3 Populate each next pointer to point to its next right node. If there
\ is no next right node, the next pointer should be set to NULL.
4
\ Initially, all next pointers are set to NULL.
5
------------------------------
------------------------------
For example, Pascal's Triangle
Given the following perfect binary tree, ------------------------------
Given numRows, generate the first numRows of Pascal's triangle.
1
/ \
2 3 For example, given numRows = 5,
/ \ / \ Return
4 5 6 7
[
[1],
[1,1],
After calling your function, the tree should look like: [1,2,1],
[1,3,3,1],
1 -> NULL [1,4,6,4,1]
/ \ ]
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL ------------------------------
------------------------------
Pascal's Triangle II
------------------------------ ------------------------------
------------------------------ Given an index k, return the kth row of the Pascal's triangle.
Populating Next Right Pointers in Each Node II
------------------------------
Follow up for problem "Populating Next Right Pointers in Each Node". For example, given k = 3,
What if the given tree could be any binary tree? Would your previous Return [1,3,3,1].
solution still work?
Note:
You may only use constant extra space. Note:
Could you optimize your algorithm to use only O(k) extra space?
[
After calling your function, the tree should look like: [2],
[3,4], stock multiple times). However, you may not engage in multiple
[6,5,7], transactions at the same time (ie, you must sell the stock before
[4,1,8,3] you buy again).
] ------------------------------
------------------------------
Best Time to Buy and Sell Stock III
------------------------------
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = Say you have an array for which the ith element is the price of a
11). given stock on day i.
Input: [7, 1, 5, 3, 6, 4]
Output: 5 For example:
Given the below binary tree,
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be
larger than buying price) 1
/ \
2 3
Example 2:
For example,
For example,
Given:
beginWord = "hit"
Given: endWord = "cog"
beginWord = "hit" wordList = ["hot","dot","dog","lot","log","cog"]
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -
> "cog",
Return return its length 5.
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"] Note:
]
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
Note: You may assume beginWord and endWord are non-empty and are not the
same.
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the UPDATE (2017/1/20):
same. The wordList parameter had been changed to a list of strings
(instead of a set of strings). Please reload the code definition to
get the latest changes.
------------------------------
------------------------------ For example,
Longest Consecutive Sequence
------------------------------ X X X X
X O O X
Given an unsorted array of integers, find the length of the longest X X O X
consecutive elements sequence. X O X X
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return After running your function, the board should be:
its length: 4.
X X X X
X X X X
Your algorithm should run in O(n) complexity. X X X X
X O X X
------------------------------
------------------------------
Sum Root to Leaf Numbers ------------------------------
------------------------------ ------------------------------
Given a binary tree containing digits from 0-9 only, each root-to- Palindrome Partitioning
leaf path could represent a number. ------------------------------
An example is the root-to-leaf path 1->2->3 which represents the
number 123. Given a string s, partition s such that every substring of the
partition is a palindrome.
Find the total sum of all root-to-leaf numbers.
1
/ \ For example, given s = "aab",
2 3
Return
[
The root-to-leaf path 1->2 represents the number 12. ["aa","b"],
The root-to-leaf path 1->3 represents the number 13. ["a","a","b"]
]
A region is captured by flipping all 'O's into 'X's in that Return the minimum cuts needed for a palindrome partitioning of s.
surrounded region.
We use # as a separator for each node, and , as a separator for node Note:
label and each neighbor of the node. The solution is guaranteed to be unique.
------------------------------
------------------------------
Candy
As an example, consider the serialized graph {0,1,2#1,2#2,2}. ------------------------------
Note:
Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory? ------------------------------
------------------------------
------------------------------ Word Break II
------------------------------ ------------------------------
Single Number II
------------------------------ Given a non-empty string s and a dictionary wordDict containing a
list of non-empty words, add spaces in s to construct a sentence
Given an array of integers, every element appears three times except where each word is a valid dictionary word. You may assume the
for one, which appears exactly once. Find that single one. dictionary does not contain duplicate words.
------------------------------
------------------------------
Return true because "leetcode" can be segmented as "leet code". Linked List Cycle II
------------------------------
Given a linked list, return the node where the cycle begins. If
UPDATE (2017/1/4): there is no cycle, return null.
The wordDict parameter had been changed to a list of strings
(instead of a set of strings). Please reload the code definition to
get the latest changes.
Note: Do not modify the linked list.
1
\
Follow up: 2
Can you solve it without using extra space? /
3
------------------------------
------------------------------
Reorder List
------------------------------ return [3,2,1].
For example, Design and implement a data structure for Least Recently Used (LRU)
Given {1,2,3,4}, reorder it to {1,4,2,3}. cache. It should support the following operations: get and put.
------------------------------
------------------------------
Binary Tree Preorder Traversal get(key) - Get the value (will always be positive) of the key if the
------------------------------ key exists in the cache, otherwise return -1.
Given a binary tree, return the preorder traversal of its nodes' put(key, value) - Set or insert the value if the key is not already
values. present. When the cache reached its capacity, it should invalidate
the least recently used item before inserting a new item.
For example:
Given binary tree {1,#,2,3}, Follow up:
Could you do both operations in O(1) time complexity?
1
\ Example:
2
/ LRUCache cache = new LRUCache( 2 /* capacity */ );
3
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
return [1,2,3]. cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
Note: Recursive solution is trivial, could you do it iteratively? cache.get(1); // returns -1 (not found)
------------------------------ cache.get(3); // returns 3
------------------------------ cache.get(4); // returns 4
Binary Tree Postorder Traversal
------------------------------
Given a binary tree, return the postorder traversal of its nodes' ------------------------------
values. ------------------------------
Insertion Sort List
------------------------------
For example: Sort a linked list using insertion sort.
Given binary tree {1,#,2,3}, ------------------------------
------------------------------
Sort List
------------------------------
Sort a linked list in O(n log n) time using constant space What constitutes a word?
complexity. A sequence of non-space characters constitutes a word.
------------------------------ Could the input string contain leading or trailing spaces?
------------------------------ Yes. However, your reversed string should not contain leading or
Max Points on a Line trailing spaces.
------------------------------ How about multiple spaces between two words?
Given n points on a 2D plane, find the maximum number of points that Reduce them to a single space in the reversed string.
lie on the same straight line.
------------------------------
------------------------------
Evaluate Reverse Polish Notation ------------------------------
------------------------------ ------------------------------
Maximum Product Subarray
Evaluate the value of an arithmetic expression in Reverse Polish ------------------------------
Notation.
Find the contiguous subarray within an array (containing at least
one number) which has the largest product.
Given an input string, reverse the string word by word. You may assume no duplicate exists in the array.
------------------------------
------------------------------
Find Minimum in Rotated Sorted Array II
For example, ------------------------------
Given s = "the sky is blue",
return "blue is sky the". Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?
B: b1 → b2 → b3
The array may contain duplicates.
------------------------------ begin to intersect at node c1.
------------------------------
Min Stack Notes:
------------------------------
If the two linked lists have no intersection at all, return null.
Design a stack that supports push, pop, top, and retrieving the The linked lists must retain their original structure after the
minimum element in constant time. function returns.
You may assume there are no cycles anywhere in the entire linked
structure.
push(x) -- Push element x onto stack. Your code should preferably run in O(n) time and use only O(1)
memory.
Example: Given an input array where num[i] ≠ num[i+1], find a peak element
and return its index.
MinStack minStack = new MinStack();
minStack.push(-2); The array may contain multiple peaks, in that case return the index
minStack.push(0); to any one of the peaks is fine.
minStack.push(-3);
minStack.getMin(); --> Returns -3. You may imagine that num[-1] = num[n] = -∞.
minStack.pop();
minStack.top(); --> Returns 0. For example, in array [1, 2, 3, 1], 3 is a peak element and your
minStack.getMin(); --> Returns -2. function should return the index number 2.
Given numerator = 1, denominator = 2, return "0.5". Credits:Special thanks to @ifanchu for adding this problem and
Given numerator = 2, denominator = 1, return "2". creating all test cases.
Given numerator = 2, denominator = 3, return "0.(6)". ------------------------------
------------------------------
Majority Element
------------------------------
Given an array of size n, find the majority element. The majority
No scary math, just apply elementary math knowledge. Still element is the element that appears more than ⌊ n/2 ⌋
remember how to perform a long division? times.
Try a long division on 4/9, the repeating part is obvious. Now try
4/333. Do you see a pattern? You may assume that the array is non-empty and the majority element
Be wary of edge cases! List out as many test cases as you can always exist in the array.
think of and test your code thoroughly.
Credits:Special thanks to @ts for adding this problem and creating
Note: next() and hasNext() should run in average O(1) time and uses
O(h) memory, where h is the height of the tree. 10
30
Credits:Special thanks to @ts for adding this problem and creating -5 (P)
all test cases.
------------------------------
------------------------------
Dungeon Game
------------------------------
Notes:
table.dungeon, .dungeon th, .dungeon td {
border:3px solid black; The knight's health has no upper bound.
} Any room can contain threats or power-ups, even the first room the
knight enters and the bottom-right room where the princess is
imprisoned. you must sell the stock before you buy again).
Note: The result may be very large, so you need to return a string
instead of an integer. [show hint]
Hint:
Credits:Special thanks to @ts for adding this problem and creating Could you do it in-place with O(1) extra space?
all test cases.
------------------------------
------------------------------ Related problem: Reverse Words in a String II
------------------------------
Repeated DNA Sequences Credits:Special thanks to @Freezen for adding this problem and
------------------------------ creating all test cases.
------------------------------
All DNA is composed of a series of nucleotides abbreviated as A, C, ------------------------------
G, and T, for example: "ACGAATTCCG". When studying DNA, it is Reverse Bits
sometimes useful to identify repeated sequences within the DNA. ------------------------------
Reverse bits of a given 32 bits unsigned integer.
Write a function to find all the 10-letter-long sequences
(substrings) that occur more than once in a DNA molecule. For example, given input 43261596 (represented in binary as
00000010100101000001111010011100), return 964176192 (represented in
binary as 00111001011110000010100101000000).
For example,
Note: For example, the 32-bit integer ’11' has binary representation
You may not engage in multiple transactions at the same time (ie, 00000000000000000000000000001011, so the function should return 3.
Credits:Special thanks to @ts for adding this problem and creating Example 1:
all test cases. 11110110101100000000
------------------------------ Answer: 1
------------------------------ Example 2:
House Robber 11000110000010000011
------------------------------ Answer: 3
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only Credits:Special thanks to @mithmatt for adding this problem and
constraint stopping you from robbing each of them is that adjacent creating all test cases.
houses have security system connected and it will automatically ------------------------------
contact the police if two adjacent houses were broken into on the ------------------------------
same night. Bitwise AND of Numbers Range
------------------------------
Given a list of non-negative integers representing the amount of Given a range [m, n] where 0 <= m <= n <= 2147483647, return the
money of each house, determine the maximum amount of money you can bitwise AND of all numbers in this range, inclusive.
rob tonight without alerting the police.
Credits:Special thanks to @ifanchu for adding this problem and For example, given the range [5, 7], you should return 4.
creating all test cases. Also thanks to @ts for adding additional
test cases.
------------------------------ Credits:Special thanks to @amrsaqr for adding this problem and
------------------------------ creating all test cases.
Binary Tree Right Side View ------------------------------
------------------------------ ------------------------------
Given a binary tree, imagine yourself standing on the right side of Happy Number
it, return the values of the nodes you can see ordered from top to ------------------------------
bottom. Write an algorithm to determine if a number is "happy".
12 + 92 = 82
82 + 22 = 68
You should return [1, 3, 4]. 62 + 82 = 100
12 + 02 + 02 = 1
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime ------------------------------
complexity is O(n log log n). For the more mathematically inclined Reverse a singly linked list.
readers, you can read more about its algorithm complexity on
Wikipedia. click to show more hints.
Hint:
public int countPrimes(int n) { A linked list can be reversed either iteratively or recursively.
boolean[] isPrime = new boolean[n]; Could you implement both?
for (int i = 2; i < n; i++) {
isPrime[i] = true; ------------------------------
} ------------------------------
// Loop's ending condition is i * i < n instead of i < sqrt(n) Course Schedule
// to avoid repeatedly calling an expensive function sqrt(). ------------------------------
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue; There are a total of n courses you have to take, labeled from 0 to n
for (int j = i * i; j < n; j += i) { - 1.
isPrime[j] = false;
} Some courses may have prerequisites, for example to take course 0
} you have to first take course 1, which is expressed as a pair: [0,1]
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++; Given the total number of courses and a list of prerequisite pairs,
} is it possible for you to finish all courses?
return count;
}
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should
------------------------------ have finished course 0. So it is possible.
------------------------------
Isomorphic Strings 2, [[1,0],[0,1]]
------------------------------ There are a total of 2 courses to take. To take course 1 you should
Given two strings s and t, determine if they are isomorphic. have finished course 0, and to take course 0 you should also have
finished course 1. So it is impossible.
Two strings are isomorphic if the characters in s can be replaced to
get t. Note:
All occurrences of a character must be replaced with another The input prerequisites is a graph represented by a list of edges,
character while preserving the order of characters. No two not adjacency matrices. Read more about how a graph is represented.
characters may map to the same character but a character may map to You may assume that there are no duplicate edges in the input
itself. prerequisites.
For example,
Given "egg", "add", return true.
click to show more hints.
Given "foo", "bar", return false.
Hints:
Given "paper", "title", return true.
This problem is equivalent to finding if a cycle exists in a
Note: directed graph. If a cycle exists, no topological ordering exists
You may assume both s and t have the same length. and therefore it will be impossible to take all courses.
------------------------------ Topological Sort via DFS - A great video tutorial (21 minutes) on
------------------------------ Coursera explaining the basic concepts of Topological Sort.
Reverse Linked List Topological sort could also be done via BFS.
There may be multiple correct orders, you just need to return one of
------------------------------ them. If it is impossible to finish all courses, return an empty
------------------------------ array.
Implement Trie (Prefix Tree)
------------------------------
For example:
Implement a trie with insert, search, and startsWith methods. 2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should
have finished course 0. So the correct course order is [0,1]
Note: 4, [[1,0],[2,0],[3,1],[3,2]]
You may assume that all inputs are consist of lowercase letters a-z. There are a total of 4 courses to take. To take course 3 you should
have finished both courses 1 and 2. Both courses 1 and 2 should be
------------------------------ taken after you finished course 0. So one correct course order is
------------------------------ [0,1,2,3]. Another correct ordering is[0,2,1,3].
Minimum Size Subarray Sum
------------------------------ Note:
Given an array of n positive integers and a positive integer s, find The input prerequisites is a graph represented by a list of edges,
the minimal length of a contiguous subarray of which the sum ≥ s. If not adjacency matrices. Read more about how a graph is represented.
there isn't one, return 0 instead. You may assume that there are no duplicate edges in the input
prerequisites.
Hints:
click to show more practice.
This problem is equivalent to finding the topological order in a
More practice: directed graph. If a cycle exists, no topological ordering exists
and therefore it will be impossible to take all courses.
If you have figured out the O(n) solution, try coding another Topological Sort via DFS - A great video tutorial (21 minutes) on
solution of which the time complexity is O(n log n). Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.
Given the total number of courses and a list of prerequisite pairs, search(word) can search a literal word or a regular expression
return the ordering of courses you should take to finish all string containing only letters a-z or .. A . means it can represent
courses. any one letter.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
For example:
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
[12 7]...] is not acceptable; the three lines of height 5 should be Definition of a complete binary tree from Wikipedia:
merged into one in the final output as such: [...[2 3], [4 5], [12 In a complete binary tree every level, except possibly the last, is
7], ...] completely filled, and all nodes in the last level are as far left
as possible. It can have between 1 and 2h nodes inclusive at the
last level h.
------------------------------
Credits:Special thanks to @stellari for adding this problem, ------------------------------
creating these two awesome images and all test cases. Rectangle Area
------------------------------ ------------------------------
------------------------------ Find the total area covered by two rectilinear rectangles in a 2D
Contains Duplicate II plane.
------------------------------ Each rectangle is defined by its bottom left corner and top right
corner as shown in the figure.
Given an array of integers and an integer k, find out whether there
are two distinct indices i and j in the array such that nums[i] =
nums[j] and the absolute difference between i and j is at most k.
------------------------------ Assume that the total area is never beyond the maximum possible
------------------------------ value of int.
Contains Duplicate III
------------------------------
Credits:Special thanks to @mithmatt for adding this problem,
Given an array of integers, find out whether there are two distinct creating the above image and all test cases.
indices i and j in the array such that the absolute difference ------------------------------
between nums[i] and nums[j] is at most t and the absolute difference ------------------------------
between i and j is at most k. Basic Calculator
------------------------------
------------------------------ Implement a basic calculator to evaluate a simple expression string.
------------------------------
Maximal Square The expression string may contain open ( and closing parentheses ),
------------------------------ the plus + or minus sign -, non-negative integers and empty
spaces .
Given a 2D binary matrix filled with 0's and 1's, find the largest
square containing only 1's and return its area. You may assume that the given expression is always valid.
Some examples:
For example, given the following matrix:
"1 + 1" = 2
1 0 1 0 0 " 2-1 + 2 " = 3
1 0 1 1 1 "(1+(4+5+2)-3)+(6+8)" = 23
1 1 1 1 1
1 0 0 1 0
Return 4.
Note: Do not use the eval built-in library function.
You must use only standard operations of a queue -- which means only
push to back, peek/pop from front, size, and is empty operations are
valid. Note: Do not use the eval built-in library function.
Depending on your language, queue may not be supported natively. You
may simulate a queue by using a list or deque (double-ended queue),
as long as you use only standard operations of a queue. Credits:Special thanks to @ts for adding this problem and creating
You may assume that all operations are valid (for example, no pop or all test cases.
top operations will be called on an empty stack). ------------------------------
------------------------------
Summary Ranges
------------------------------
Credits:Special thanks to @jianchao.li.fighter for adding this
problem and all test cases. Given a sorted integer array without duplicates, return the summary
------------------------------ of its ranges.
------------------------------
Invert Binary Tree
------------------------------ For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Invert a binary tree.
4
/ \ Credits:Special thanks to @jianchao.li.fighter for adding this
2 7 problem and creating all test cases.
/ \ / \ ------------------------------
1 3 6 9 ------------------------------
Majority Element II
to ------------------------------
4 Given an integer array of size n, find all elements that appear more
/ \ than ⌊ n/3 ⌋ times. The algorithm should run in linear
7 2 time and in O(1) space.
/ \ / \
9 6 3 1
How many majority elements could it possibly have?
Trivia: Do you have a better hint? Suggest it!
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), ------------------------------
but you can’t invert a binary tree on a whiteboard so fuck off. ------------------------------
------------------------------ Kth Smallest Element in a BST
------------------------------ ------------------------------
Basic Calculator II Given a binary search tree, write a function kthSmallest to find the
------------------------------ kth smallest element in it.
Implement a basic calculator to evaluate a simple expression string.
For example:
Credits:Special thanks to @ts for adding this problem and creating Given n = 13,
all test cases. Return 6, because digit 1 occurred in the following numbers: 1, 10,
------------------------------ 11, 12, 13.
------------------------------
Power of Two
------------------------------
Beware of overflow.
Given an integer, write a function to determine if it is a power of
two. ------------------------------
------------------------------
Palindrome Linked List
Credits:Special thanks to @jianchao.li.fighter for adding this ------------------------------
problem and creating all test cases. Given a singly linked list, determine if it is a palindrome.
------------------------------
------------------------------ Follow up:
Implement Queue using Stacks Could you do it in O(n) time and O(1) space?
------------------------------ ------------------------------
------------------------------
Implement the following operations of a queue using stacks. Lowest Common Ancestor of a Binary Search Tree
------------------------------
push(x) -- Push element x to the back of queue. Given a binary search tree (BST), find the lowest common ancestor
(LCA) of two given nodes in the BST.
Notes: _______6______
/ \
You must use only standard operations of a stack -- which means only ___2__ ___8__
push to top, peek/pop from top, size, and is empty operations are / \ / \
valid. 0 _4 7 9
Depending on your language, stack may not be supported natively. You / \
may simulate a stack by using a list or deque (double-ended queue), 3 5
Given an array of n integers where n > 1, nums, return an array
output such that output[i] is equal to the product of all the
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. elements of nums except nums[i].
Another example is LCA of nodes 2 and 4 is 2, since a node can be a
descendant of itself according to the LCA definition. Solve it without division and in O(n).
------------------------------
------------------------------ For example, given [1,2,3,4], return [24,12,8,6].
Lowest Common Ancestor of a Binary Tree
------------------------------ Follow up:
Could you solve it with constant space complexity? (Note: The output
Given a binary tree, find the lowest common ancestor (LCA) of two array does not count as extra space for the purpose of space
given nodes in the tree. complexity analysis.)
------------------------------
------------------------------
Sliding Window Maximum
According to the definition of LCA on Wikipedia: “The lowest common ------------------------------
ancestor is defined between two nodes v and w as the lowest node in Given an array nums, there is a sliding window of size k which is
T that has both v and w as descendants (where we allow a node to be moving from the very left of the array to the very right. You can
a descendant of itself).” only see the k numbers in the window. Each time the sliding window
moves right by one position.
For example,
_______3______ Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
/ \
___5__ ___1__
/ \ / \ Window position Max
6 _2 0 8 --------------- -----
/ \ [1 3 -1] -3 5 3 6 7 3
7 4 1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. 1 3 -1 -3 5 [3 6 7] 7
Another example is LCA of nodes 5 and 4 is 5, since a node can be a
descendant of itself according to the LCA definition.
------------------------------ Therefore, return the max sliding window as [3,3,5,5,6,7].
------------------------------
Delete Node in a Linked List Note:
------------------------------ You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for
non-empty array.
Write a function to delete a node (except the tail) in a singly
linked list, given only access to that node. Follow up:
Could you solve it in linear time?
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the How about using a data structure such as deque (double-ended
third node with value 3, the linked list should become 1 -> 2 -> 4 queue)?
after calling your function. The queue size need not be the same as the window’s size.
Remove redundant elements and the queue should store only elements
------------------------------ that need to be considered.
------------------------------
Product of Array Except Self ------------------------------
------------------------------ ------------------------------
Integers in each row are sorted in ascending from left to right. For example,
Integers in each column are sorted in ascending from top to bottom. s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
For example, You may assume the string contains only lowercase alphabets.
Example 2
Input: "2*3-4*5" 1
(2*(3-(4*5))) = -34 / \
((2*3)-(4*5)) = -14 2 3
((2*(3-4))*5) = -10 \
(2*((3-4)*5)) = -10 5
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
Credits:Special thanks to @mithmatt for adding this problem and All root-to-leaf paths are:
creating all test cases. ["1->2->5", "1->3"]
The order of the result is not important. So in the above example,
[5, 3] is also correct.
Credits:Special thanks to @jianchao.li.fighter for adding this Your algorithm should run in linear runtime complexity. Could you
problem and creating all test cases. implement it using only constant space complexity?
------------------------------
------------------------------
Add Digits
------------------------------ Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases.
Given a non-negative integer num, repeatedly add all its digits ------------------------------
until the result has only one digit. ------------------------------
------------------------------
Ugly Number
------------------------------
For example:
Write a program to check whether a given number is an ugly number.
Did you see a pattern in dividing the number into chunk of words?
return all possibilities to add binary operators (not unary) +, -,
Expected runtime complexity is in O(log n) and the input is or * between the digits so they evaluate to the target value.
sorted.
------------------------------ Examples:
------------------------------ "123", 6 -> ["1+2+3", "1*2*3"]
------------------------------ "232", 8 -> ["2*3+2", "2+3*2"]
------------------------------ "105", 5 -> ["1*0+5","10-5"]
First Bad Version "00", 0 -> ["0+0", "0-0", "0*0"]
------------------------------ "3456237490", 9191 -> []
Given a string that contains only digits 0-9 and a target value, Now you call peek() and it returns 2, the next element. Calling
next() after that still return 2. mathematician John Horton Conway in 1970."
You call next() the final time and it returns 3, the last element.
Calling hasNext() after that should return false.
Given a board with m by n cells, each cell has an initial state live
(1) or dead (0). Each cell interacts with its eight neighbors
Think of "looking ahead". You want to cache the next element. (horizontal, vertical, diagonal) using the following four rules
Is one variable sufficient? Why or why not? (taken from the above Wikipedia article):
Test your design with call order of peek() before next() vs next()
before peek().
For a clean implementation, check out Google's guava library
source code.
Any live cell with fewer than two live neighbors dies, as if caused
by under-population.
Any live cell with two or three live neighbors lives on to the next
Follow up: How would you extend your design to be generic and work generation.
with all types, not just integer? Any live cell with more than three live neighbors dies, as if by
over-population..
Credits:Special thanks to @porker2008 for adding this problem and Any dead cell with exactly three live neighbors becomes a live cell,
creating all test cases. as if by reproduction.
------------------------------
------------------------------
------------------------------
------------------------------
Find the Duplicate Number Write a function to compute the next state (after one update) of the
------------------------------ board given its current state.
Notes:
You may assume pattern contains only lowercase letters, and str void addNum(int num) - Add a integer number from the data stream to
contains lowercase letters separated by a single space. the data structure.
double findMedian() - Return the median of all elements so far.
Note: Do not use class member/global/static variables to store Given an unsorted array of integers, find the length of longest
states. Your serialize and deserialize algorithms should be increasing subsequence.
stateless.
For example,
Credits:Special thanks to @Louis1992 for adding this problem and Given [10, 9, 2, 5, 3, 7, 101, 18],
creating all test cases. The longest increasing subsequence is [2, 3, 7, 101], therefore the
------------------------------ length is 4. Note that there may be more than one LIS combination,
------------------------------ it is only necessary for you to return the length.
------------------------------
Bulls and Cows
------------------------------ Your algorithm should run in O(n2) complexity.
You are playing the following Bulls and Cows game with your friend:
You write down a number and ask your friend to guess what the number
is. Each time your friend makes a guess, you provide a hint that Follow up: Could you improve it to O(n log n) time complexity?
indicates how many digits in said guess match your secret number
exactly in both digit and position (called "bulls") and how many Credits:Special thanks to @pbrother for adding this problem and
digits match the secret number but locate in the wrong position creating all test cases.
(called "cows"). Your friend will use successive guesses and hints ------------------------------
to eventually derive the secret number. ------------------------------
Remove Invalid Parentheses
------------------------------
For example:
Remove the minimum number of invalid parentheses in order to make
Secret number: "1807" the input string valid. Return all possible results.
Friend's guess: "7810"
Note: The input string may contain letters other than the
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) parentheses ( and ).
Note:
For example:
You may assume that the array does not change. "112358" is an additive number because the digits can form an
There are many calls to sumRange function. additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199" is also an additive number, the additive sequence is: 1,
------------------------------ 99, 100, 199.
------------------------------ 1 + 99 = 100, 99 + 100 = 199
Range Sum Query 2D - Immutable
------------------------------
Given a 2D matrix matrix, find the sum of the elements inside the
rectangle defined by its upper left corner (row1, col1) and lower Note: Numbers in the additive sequence cannot have leading zeros, so
right corner (row2, col2). sequence 1, 2, 03 or 1, 02, 3 is invalid.
Follow up:
Example: How would you handle overflow for very large input integers?
Given matrix = [
[3, 0, 1, 4, 2], Credits:Special thanks to @jeantimex for adding this problem and
[5, 6, 3, 2, 1], creating all test cases.
[1, 2, 0, 1, 5], ------------------------------
[4, 1, 0, 1, 7], ------------------------------
[1, 0, 3, 0, 5] Range Sum Query - Mutable
] ------------------------------
Given an integer array nums, find the sum of the elements between
sumRegion(2, 1, 4, 3) -> 8 indices i and j (i ≤ j), inclusive.
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12 The update(i, val) function modifies nums by updating the element at
index i to val.
Example:
Note:
Given nums = [1, 3, 5]
You may assume that the matrix does not change.
There are many calls to sumRegion function. sumRange(0, 2) -> 9
You may assume that row1 ≤ row2 and col1 ≤ col2. update(1, 2)
sumRange(0, 2) -> 8
------------------------------
------------------------------
------------------------------ Note:
The array is only modifiable by the update function. Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
You may assume the number of calls to update and sumRange function
is distributed evenly.
0 1 2
\ | /
------------------------------ 3
------------------------------ |
------------------------------ 4
Minimum Height Trees |
------------------------------ 5
Note:
Format
The graph contains n nodes which are labeled from 0 to n - 1.
You will be given the number n and a list of undirected edges (1) According to the definition
(each edge is a pair of labels). of tree on Wikipedia: “a tree is an undirected graph in which
any two vertices are connected by
exactly one path. In other words, any connected graph without
You can assume that no duplicate edges will appear in edges. Since simple cycles is a tree.”
all edges are
undirected, [0, 1] is the same as [1, 0] and thus will not
appear together in (2) The height of a rooted tree is the number of edges on the
edges. longest downward path between the root and a
leaf.
Example 1:
Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] ------------------------------
------------------------------
------------------------------
Burst Balloons
0 ------------------------------
|
1 Given n balloons, indexed from 0 to n-1. Each balloon is painted
/ \ with a
2 3 number on it represented by array nums.
You are asked to burst all the balloons. If the you burst
return [1] balloon i you will get nums[left] * nums[i] * nums[right] coins.
Here left
and right are adjacent indices of i. After the burst, the left
and right
Example 2: then becomes adjacent.
Credits:Special thanks to @dietpepsi for adding this problem and
Find the maximum coins you can collect by bursting the balloons creating all test cases.
wisely. ------------------------------
------------------------------
------------------------------
Note: Count of Smaller Numbers After Self
(1) You may imagine nums[-1] = nums[n] = 1. They are not real ------------------------------
therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 You are given an integer array nums and you have to return a new
counts array.
The counts array has the property where counts[i] is
the number of smaller elements to the right of nums[i].
Example:
Example:
Given [3, 1, 5, 8]
Given nums = [5, 2, 6, 1]
Return 167 To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] To the right of 1 there is 0 smaller element.
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
Credits:Special thanks to @dietpepsi for adding this problem and Return the array [2, 1, 1, 0].
creating all test cases.
------------------------------ ------------------------------
------------------------------ ------------------------------
Super Ugly Number Remove Duplicate Letters
------------------------------ ------------------------------
Write a program to find the nth super ugly number. Given a string which contains only lowercase letters, remove
duplicate letters so that every letter appear once and only once.
You must make sure your result is the smallest in lexicographical
order among all possible results.
Super ugly numbers are positive numbers whose all prime factors
are in the given prime list
primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19,
26, 28, 32] Example:
is the sequence of the first 12 super ugly numbers given primes
= [2, 7, 13, 19] of size 4.
Given "bcabc"
Return "abc"
Note:
(1) 1 is a super ugly number for any given primes. Given "cbacdcbc"
(2) The given numbers in primes are in ascending order. Return "acdb"
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
(4) The nth super ugly number is guaranteed to fit in a 32-bit
signed integer. Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
------------------------------
------------------------------
------------------------------ Example:
Maximum Product of Word Lengths
------------------------------ Given n = 3.
At first, the three bulbs are [off, off, off].
Given a string array words, find the maximum value of After first round, the three bulbs are [on, on, on].
length(word[i]) * length(word[j]) where the two words do not share After second round, the three bulbs are [on, off, on].
common letters. After third round, the three bulbs are [on, off, off].
You may assume that each word will contain only lower case So you should return 1, because there is only one bulb is on.
letters.
If no such two words exist, return 0. ------------------------------
------------------------------
------------------------------
Create Maximum Number
Example 1: ------------------------------
nums1 = [6, 7]
Credits:Special thanks to @dietpepsi for adding this problem and nums2 = [6, 0, 4]
creating all test cases. k = 5
------------------------------ return [6, 7, 6, 0, 4]
------------------------------
Bulb Switcher
------------------------------ Example 3:
There are n bulbs that are initially off. You first turn on all the
bulbs. Then, you turn off every second bulb. On the third round, you nums1 = [3, 9]
toggle every third bulb (turning on if it's off or turning off if nums2 = [8, 9]
it's on). For the ith round, you toggle every i bulb. For the nth k = 3
round, you only toggle the last bulb. return [9, 8, 9]
Credits:Special thanks to @jianchao.li.fighter for adding this Given an integer array nums, return the number of range sums
problem and creating all test cases. that lie in [lower, upper] inclusive.
------------------------------
------------------------------ Range sum S(i, j) is defined as the sum of the elements in nums
------------------------------ between indices i and
Wiggle Sort II j (i ≤ j), inclusive.
------------------------------
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, Example:
4, 1, 5, 1, 6]. Given nums = [-2, 5, -1], lower = -2, upper = 2,
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, Return 3.
3, 1, 3, 1, 2]. The three ranges are : [0, 0], [2, 2], [0, 2] and their
respective sums are: -2, -1, 2.
Return 4
Example:
Given 1->2->3->4->5->NULL, The longest increasing path is [3, 4, 5, 6]. Moving diagonally is
return 1->3->5->2->4->NULL. not allowed.
Combinations of nums are [1], [3], [1,3], which form possible sums
From each cell, you can either move to four directions: left, right, of: 1, 3, 4.
up or down. You may NOT move diagonally or move outside of the Now if we add/patch 2 to nums, the combinations are: [1], [2], [3],
boundary (i.e. wrap-around is not allowed). [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1,
6].
Example 1: So we only need 1 patch.
nums = [ Example 2:
[9,9,4], nums = [1, 5, 10], n = 20
[6,6,8], Return 2.
[2,1,1] The two patches can be [2, 4].
]
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
_9_
/ \
3 2
/ \/ \ Example 1:
4 # 6 1 tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"],
/ \ / \ / \ ["LHR", "SFO"]]
# # # # # # Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
For example, the above binary tree can be serialized to the string Example 2:
"9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],
["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Given a string of comma separated values, verify whether it is a Another possible reconstruction is
correct preorder traversal serialization of a binary tree. Find an ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical
algorithm without reconstructing the tree. order.
If there are multiple valid itineraries, you should return the Given [5, 4, 3, 2, 1],
itinerary that has the smallest lexical order when read as a single return false.
string. For example, the itinerary ["JFK", "LGA"] has a smaller
└───┼>
Credits:Special thanks to @DjangoUnchained for adding this problem
and creating all test cases. Return true (self crossing)
------------------------------
------------------------------
Self Crossing
------------------------------ Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
You are given an array x of n positive numbers. You start at ------------------------------
point (0,0) and moves x[0] metres to the north, then x[1] metres to ------------------------------
the west, Palindrome Pairs
x[2] metres to the south, ------------------------------
x[3] metres to the east and so on. In other words, after each
move your direction changes Given a list of unique words, find all pairs of distinct indices
counter-clockwise. (i, j) in the given list, so that the concatenation of the two
words, i.e. words[i] + words[j] is a palindrome.
Determine the maximum amount of money the thief can rob tonight
without alerting the police.
Example 3:
Maximum amount of money the thief can rob = 4 + 5 = 9. By calling next repeatedly until hasNext returns false, the order of
elements returned by next should be: [1,1,2,1,1].
For example,
Note: You may assume that n is not less than 2 and not larger than Given [1,1,1,2,2,3] and k = 2, return [1,2].
58.
Note:
There is a simple O(n) solution to this problem. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
You may check the breaking results of n ranging from 7 to 10 to Your algorithm's time complexity must be better than O(n log n),
discover the regularities. where n is the array's size.
------------------------------
Credits:Special thanks to @jianchao.li.fighter for adding this ------------------------------
problem and creating all test cases. ------------------------------
------------------------------ Intersection of Two Arrays
------------------------------ ------------------------------
Reverse String
------------------------------ Given two arrays, write a function to compute their intersection.
Write a function that takes a string as input and returns the string
reversed.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Example:
Given s = "hello", return "olleh".
Note:
------------------------------
------------------------------ Each element in the result must be unique.
Reverse Vowels of a String The result can be in any order.
------------------------------
Write a function that takes a string as input and reverse only the
vowels of a string. ------------------------------
------------------------------
Intersection of Two Arrays II
Example 1: ------------------------------
Given s = "hello", return "holle".
Given two arrays, write a function to compute their intersection.
Example 2: Example:
Given s = "leetcode", return "leotcede". Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Note:
The vowels does not include the letter "y". Each element in the result should appear as many times as it shows
in both arrays.
------------------------------ The result can be in any order.
------------------------------
------------------------------
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of
Follow up: envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
What if the given array is already sorted? How would you optimize ------------------------------
your algorithm? ------------------------------
What if nums1's size is small compared to nums2's size? Which Design Twitter
algorithm is better? ------------------------------
What if elements of nums2 are stored on disk, and the memory is Design a simplified version of Twitter where users can post tweets,
limited such that you cannot load all elements into the memory at follow/unfollow another user and is able to see the 10 most recent
once? tweets in the user's news feed. Your design should support the
following methods:
------------------------------
------------------------------
------------------------------ postTweet(userId, tweetId): Compose a new tweet.
Data Stream as Disjoint Intervals getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the
------------------------------ user's news feed. Each item in the news feed must be posted by users
Given a data stream input of non-negative integers a1, a2, ..., who the user followed or by the user herself. Tweets must be ordered
an, ..., summarize the numbers seen so far as a list of disjoint from most recent to least recent.
intervals. follow(followerId, followeeId): Follower follows a followee.
unfollow(followerId, followeeId): Follower unfollows a followee.
For example, suppose the integers from the data stream are 1, 3, 7,
2, 6, ..., then the summary will be:
[1, 1] Example:
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7] Twitter twitter = new Twitter();
[1, 3], [7, 7]
[1, 3], [6, 7] // User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);
Follow up: // User 1's news feed should return a list with 1 tweet id -> [5].
What if there are lots of merges and the number of disjoint twitter.getNewsFeed(1);
intervals are small compared to the data stream's size?
// User 1 follows user 2.
twitter.follow(1, 2);
Credits:Special thanks to @yunhong for adding this problem and
creating most of the test cases. // User 2 posts a new tweet (id = 6).
------------------------------ twitter.postTweet(2, 6);
------------------------------
------------------------------ // User 1's news feed should return a list with 2 tweet ids -> [6,
Russian Doll Envelopes 5].
------------------------------ // Tweet id 6 should precede tweet id 5 because it is posted after
You have a number of envelopes with widths and heights given as a tweet id 5.
pair of integers (w, h). One envelope can fit into another if and twitter.getNewsFeed(1);
only if both the width and height of one envelope is greater than
the width and height of the other envelope. // User 1 unfollows user 2.
twitter.unfollow(1, 2);
What is the maximum number of envelopes can you Russian doll? (put // User 1's news feed should return a list with 1 tweet id -> [5],
one inside other) // since user 1 is no longer following user 2.
twitter.getNewsFeed(1);
Example:
------------------------------ Pour water from one jug into another till the other jug is
------------------------------ completely full or the first jug itself is empty.
------------------------------
------------------------------
------------------------------
------------------------------ Example 1: (From the famous "Die Hard" example)
------------------------------
------------------------------ Input: x = 3, y = 5, z = 4
Max Sum of Rectangle No Larger Than K Output: True
------------------------------
Given a non-empty 2D matrix matrix and an integer k, find the max
sum of a rectangle in the matrix such that its sum is no larger than
k. Example 2:
Example: Input: x = 2, y = 6, z = 5
Given matrix = [ Output: False
[1, 0, 1],
[0, -2, 3]
]
k = 2 Credits:Special thanks to @vinod23 for adding this problem and
creating all test cases.
------------------------------
------------------------------
The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 ------------------------------
and 2 is the max number no larger than k (k = 2). Valid Perfect Square
------------------------------
Note: Given a positive integer num, write a function which returns True if
num is a perfect square else False.
The rectangle inside the matrix must have an area > 0.
What if the number of rows is much larger than the number of
columns? Note: Do not use any built-in library function such as sqrt.
Example 1:
Credits:Special thanks to @fujiaozhu for adding this problem and
creating all test cases. Input: 16
------------------------------ Returns: True
------------------------------
------------------------------
Water and Jug Problem
------------------------------ Example 2:
You are given two jugs with capacities x and y litres. There is an
infinite amount of water supply available. Input: 14
You need to determine whether it is possible to measure exactly z Returns: False
litres using these two jugs.
Example 1: a = 2
b = [1,0]
nums: [1,2,3]
Result: 1024
Result: [1,2] (of course, [1,3] will also be ok)
You are given two integer arrays nums1 and nums2 sorted in ascending
order and an integer k.
Credits:Special thanks to @Stomach_ache for adding this problem and
creating all test cases.
------------------------------ Define a pair (u,v) which consists of one element from the first
------------------------------ array and one element from the second array.
------------------------------
------------------------------ Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Sum of Two Integers
------------------------------
Calculate the sum of two integers a and b, but you are not allowed Example 1:
to use the operator + and -.
Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Example:
Given a = 1 and b = 2, return 3. Return: [1,2],[1,4],[1,6]
a = 2
Example 3:
All possible pairs are returned from the sequence: First round: You guess 5, I tell you that it's higher. You pay $5.
[1,3],[2,3] Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round: You guess 9, I tell you that it's lower. You pay $9.
Input: [1,7,4,9,2,5] Credits:Special thanks to @pbrother for adding this problem and
Output: 6 creating all test cases.
The entire sequence is a wiggle sequence. ------------------------------
------------------------------
Input: [1,17,5,10,13,15,10,5,16,8] Kth Smallest Element in a Sorted Matrix
Output: 7 ------------------------------
There are several subsequences that achieve this length. One is Given a n x n matrix where each of the rows and columns are sorted
[1,17,10,13,10,16,8]. in ascending order, find the kth smallest element in the matrix.
Input: [1,2,3,4,5,6,7,8,9]
Output: 2 Note that it is the kth smallest element in the sorted order, not
the kth distinct element.
Example:
// Inserts 2 to the set, returns true. Set now contains [1,2]. // Removes 1 from the collection, returns true. Collection now
randomSet.insert(2); contains [1,2].
collection.remove(1);
// getRandom should return either 1 or 2 randomly.
randomSet.getRandom(); // getRandom should return 1 and 2 both equally likely.
collection.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
------------------------------
// 2 was already in the set, so return false. ------------------------------
randomSet.insert(2); Linked List Random Node
------------------------------
// Since 2 is the only number in the set, getRandom always return 2. Given a singly linked list, return a random node's value from the
randomSet.getRandom(); linked list. Each node must have the same probability of being
chosen.
Example:
------------------------------
// Init an empty collection. ------------------------------
RandomizedCollection collection = new RandomizedCollection(); Ransom Note
------------------------------
// Inserts 1 to the collection. Returns true as the collection did
not contain 1. Given an arbitrary ransom note string and another string containing
collection.insert(1); letters from all the magazines, write a function that will return
true if the ransom
// Inserts another 1 to the collection. Returns false as the note can be constructed from the magazines ; otherwise, it will
collection contained 1. Collection now contains [1,1]. return false.
collection.insert(1);
Each letter in the magazine string can only be used once in your
ransom note.
Example 1:
Note:
You may assume that both strings contain only lowercase letters. Given s = "324",
// Resets the array back to its original configuration [1,2,3]. Given an integer n, return 1 - n in lexicographical order.
solution.reset();
------------------------------
------------------------------ Please optimize your algorithm to use less time and space. The input
Mini Parser size may be as large as 5,000,000.
------------------------------
Given a nested list of integers represented as a string, implement a ------------------------------
parser to deserialize it. ------------------------------
First Unique Character in a String
Each element is either an integer, or a list -- whose elements may ------------------------------
also be integers or other lists.
Given a string, find the first non-repeating character in it and
Note: return it's index. If it doesn't exist, return -1.
You may assume that the string is well-formed:
Examples:
String is non-empty.
String does not contain white spaces. s = "leetcode"
String contains only digits 0-9, [, - ,, ]. return 0.
s = "loveleetcode", Note:
return 2.
The name of a file contains at least a . and an extension.
The name of a directory or sub-directory will not contain a ..
Note: You may assume the string contain only lowercase letters.
Time complexity required: O(n) where n is the size of the input
------------------------------ string.
------------------------------
Longest Absolute File Path Notice that a/aa/aaa/file1.txt is not the longest file path, if
------------------------------ there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
Suppose we abstract our file system by a string in the following ------------------------------
manner: ------------------------------
Find the Difference
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: ------------------------------
dir Given two strings s and t which consist of only lowercase letters.
subdir1
subdir2 String t is generated by random shuffling string s and then add one
file.ext more letter at a random position.
dir Output:
subdir1 e
file1.ext
subsubdir1 Explanation:
subdir2 'e' is the letter that was added.
subsubdir2
file2.ext ------------------------------
------------------------------
Elimination Game
The directory dir contains two sub-directories subdir1 and subdir2. ------------------------------
subdir1 contains a file file1.ext and an empty second-level sub-
directory subsubdir1. subdir2 contains a second-level sub-directory There is a list of sorted integers from 1 to n. Starting from left
subsubdir2 containing a file file2.ext. to right, remove the first number and every other number afterward
until you reach the end of the list.
We are interested in finding the longest (number of characters)
absolute path to a file within our file system. For example, in the Repeat the previous step again, but this time from right to left,
second example above, the longest absolute path is "dir/subdir2/ remove the right most number and every other number from the
subsubdir2/file2.ext", and its length is 32 (not including the remaining numbers.
double quotes).
We keep repeating the steps again, alternating left to right and
Given a string representing the file system in the above format, right to left, until a single number remains.
return the length of the longest absolute path to file in the
abstracted file system. If there is no file in the system, return 0. Find the last number that remains starting with a list of length n.
[3,1,4,2],
Example: [3,2,4,4]
]
Input:
n = 9, Return false. Because there is a gap between the two rectangular
1 2 3 4 5 6 7 8 9 regions.
2 4 6 8
2 6
6
Output:
6
Example 3:
------------------------------ rectangles = [
------------------------------ [1,1,3,3],
Perfect Rectangle [3,1,4,2],
------------------------------ [1,3,2,4],
[3,2,4,4]
Given N axis-aligned rectangles where N > 0, determine if they all ]
together form an exact cover of a rectangular region.
Return false. Because there is a gap in the top center.
rectangles = [
Example 1: [1,1,3,3],
[3,1,4,2],
rectangles = [ [1,3,2,4],
[1,1,3,3], [2,2,4,4]
[3,1,4,2], ]
[3,2,4,4],
[1,3,2,4], Return false. Because two of the rectangles overlap with each other.
[2,3,3,4]
]
Example 2:
rectangles = [ You may assume that there is only lower case English letters in both
[1,1,2,3], s and t. t is potentially a very long (length ~= 500,000) string,
[1,3,2,4], and s is a short string (<=100).
Example 1:
s = "abc", t = "ahbgdc"
Example 1:
Return true. data = [197, 130, 1], which represents the octet sequence: 11000101
10000010 00000001.
Return false.
Credits:Special thanks to @pbrother for adding this problem and Return false.
creating all test cases. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-
------------------------------ bytes character.
------------------------------ The next byte is a continuation byte which starts with 10 and that's
UTF-8 Validation correct.
------------------------------ But the second continuation byte does not start with 10, so it is
A character in UTF8 can be from 1 to 4 bytes long, subjected to the invalid.
following rules:
For 1-byte character, the first bit is a 0, followed by its unicode ------------------------------
code. ------------------------------
For n-bytes character, the first n-bits are all one's, the n+1 bit Decode String
is 0, followed by n-1 bytes with most significant 2 bits being 10. ------------------------------
This is how the UTF-8 encoding would work: Given an encoded string, return it's decoded string.
Examples:
------------------------------ Note:
------------------------------ n is guaranteed to be less than 105.
Longest Substring with At Least K Repeating Characters
------------------------------
Example:
Find the length of the longest substring T of a given string
(consists of lowercase letters only) such that every character in T A = [4, 3, 2, 6]
appears no less than k times.
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
Example 1: F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
Input:
s = "aaabb", k = 3 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
Output:
3 ------------------------------
------------------------------
The longest substring is "aaa", as 'a' is repeated 3 times. Integer Replacement
------------------------------
Input:
s = "ababbc", k = 2
If n is even, replace n with n/2.
Output: If n is odd, you can replace n with either n + 1 or n - 1.
5
------------------------------
------------------------------
Rotate Function
------------------------------ Example 1:
Example 2: Example:
Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a
Input: = ?, a / e = ?, a / a = ?, x / x = ? . return [6.0, 0.5, -1.0,
7 1.0, -1.0 ].
Output:
4 The input is: vector<pair<string, string>> equations,
vector<double>& values, vector<pair<string,
Explanation: string>> queries , where equations.size() == values.size(),
7 -> 8 -> 4 -> 2 -> 1 and the values are positive. This represents the equations. Return
or vector<double>.
7 -> 6 -> 3 -> 2 -> 1
Note: ------------------------------
The array size can be very large. Solution that uses too much extra ------------------------------
space will not pass the judge. Nth Digit
------------------------------
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5,
Example: 6, 7, 8, 9, 10, 11, ...
// pick(1) should return 0. Since in the array only nums[0] is equal Input:
to 1. 3
solution.pick(1);
Output:
3
------------------------------
------------------------------
The length of num is less than 10002 and will be ≥ k.
Example 2: The given num does not contain any leading zero.
Input:
11
Output: Example 1:
0
Input: num = "1432219", k = 3
Explanation: Output: "1219"
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Explanation: Remove the three digits 4, 3, and 2 to form the new
11, ... is a 0, which is part of the number 10. number 1219 which is the smallest.
------------------------------
------------------------------ Example 2:
Binary Watch
------------------------------ Input: num = "10200", k = 1
A binary watch has 4 LEDs on the top which represent the hours Output: "200"
(0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Explanation: Remove the leading 1 and the number is 200. Note that
Each LED represents a zero or one, with the least significant bit on the output must not contain leading zeroes.
the right.
Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone, Example 1:
4 units to the 7th stone, and 5 units to the 8th stone.
Input:
26
Example 2: Output:
"1a"
[0,1,2,3,4,8,9,11]
Input:
------------------------------ -1
------------------------------
Sum of Left Leaves Output:
------------------------------ "ffffffff"
Find the sum of all left leaves in a given binary tree.
Example: ------------------------------
------------------------------
3 Queue Reconstruction by Height
/ \ ------------------------------
9 20 Suppose you have a random list of people standing in a queue. Each
/ \ person is described by a pair of integers (h, k), where h is the
15 7 height of the person and k is the number of people in front of this
person who have a height greater than or equal to h. Write an
There are two left leaves in the binary tree, with values 9 and 15 algorithm to reconstruct the queue.
respectively. Return 24.
Note:
------------------------------ The number of people is less than 1,100.
------------------------------
Convert a Number to Hexadecimal
------------------------------ Example
------------------------------ Example:
------------------------------
Trapping Rain Water II Input:
------------------------------ "abccccdd"
Given an m x n matrix of positive integers representing the height
of each unit cell in a 2D elevation map, compute the volume of water Output:
it is able to trap after raining. 7
Explanation:
Note: One longest palindrome that can be built is "dccaccd", whose length
Both m and n are less than 110. The height of each unit cell is is 7.
greater than 0 and is less than 20,000.
------------------------------
Example: ------------------------------
Split Array Largest Sum
Given the following 3x6 height map: ------------------------------
[ Given an array which consists of non-negative integers and an
[1,4,3,1,3,2], integer m, you can split the array into m non-empty continuous
[3,2,1,3,2,4], subarrays. Write an algorithm to minimize the largest sum among
[2,3,3,2,3,1] these m subarrays.
]
Return 4. Note:
If n is the length of array, assume the following constraints are
satisfied:
Examples:
Input:
After the rain, water are trapped between the blocks. The total nums = [7,2,5,10,8]
volume of water trapped is 4. m = 2
------------------------------ Output:
------------------------------ 18
------------------------------
Longest Palindrome Explanation:
------------------------------ There are four ways to split nums into two subarrays.
Given a string which consists of lowercase or uppercase letters, The best way is to split it into [7,2,5] and [10,8],
find the length of the longest palindromes that can be built with where the largest sum among the two subarrays is only 18.
those letters.
Return: ------------------------------
[ ------------------------------
"1", Third Maximum Number
"2", ------------------------------
"Fizz", Given a non-empty array of integers, return the third maximum number
"4", in this array. If it does not exist, return the maximum number. The
"Buzz", time complexity must be in O(n).
"Fizz",
"7", Example 1:
"8",
"Fizz", Input: [3, 2, 1]
"Buzz",
"11", Output: 1
"Fizz",
"13", Explanation: The third maximum is 1.
"14",
"FizzBuzz"
]
Example 2:
Explanation: Note that the third maximum here means the third
A zero-indexed array A consisting of N numbers is given. A slice of maximum distinct number.
that array is any pair of integers (P, Q) such that 0 <= P < Q < N. Both numbers with value 2 are both considered as second maximum.
The length of both num1 and num2 is < 5100. Find the list of grid coordinates where water can flow to both the
Both num1 and num2 contains only digits 0-9. Pacific and Atlantic ocean.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the Note:
inputs to integer directly.
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
------------------------------
------------------------------
Partition Equal Subset Sum Example:
------------------------------
Given a non-empty array containing only positive integers, find if Given the following 5x5 matrix:
the array can be partitioned into two subsets such that the sum of
elements in both subsets is equal. Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
Note: ~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
Each of the array element will not exceed 100. ~ (5) 1 1 2 4 *
The array size will not exceed 200. * * * * * Atlantic
Return:
Example 1: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions
with parentheses in above matrix).
Input: [1, 5, 11, 5]
Output: false You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other
Explanation: The array cannot be partitioned into equal sum subsets. words, they can only be made of the shape 1xN (1 row, N columns) or
Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two
------------------------------ battleships - there are no adjacent battleships.
------------------------------
Pacific Atlantic Water Flow
------------------------------ Example:
This is an invalid board that you will not receive - as battleships Note:
will always have a cell separating between them.
Input contains only lowercase English letters.
Follow up:Could you do it in one-pass, using only O(1) extra memory Input is guaranteed to be valid and can be transformed to its
and without modifying the value of the board? original digits. That means invalid inputs such as "abc" or "zerone"
------------------------------ are not permitted.
------------------------------ Input length is less than 50,000.
Strong Password Checker
------------------------------
A password is considered strong if below conditions are all met:
Example 1:
Example:
Output: 28 Input:
s = "ABAB", k = 2
Output: Please note that the string does not contain any non-printable
4 characters.
Explanation: Example:
Replace the two 'A's with two 'B's or vice versa.
Input: "Hello, my name is John"
Output: 5
Example 2: ------------------------------
------------------------------
Input: Non-overlapping Intervals
s = "AABABBA", k = 1 ------------------------------
You may assume the interval's end point is always bigger than its
------------------------------ start point.
------------------------------ Intervals like [1,2] and [2,3] have borders "touching" but they
------------------------------ don't overlap each other.
All O`one Data Structure
------------------------------
Implement a data structure supporting the following operations:
Example 1:
Output: 2
Challenge: Perform all these in O(1) time complexity. Explanation: You need to remove two [1,2] to make the rest of
intervals non-overlapping.
------------------------------
------------------------------
Number of Segments in a String
------------------------------ Example 3:
Count the number of segments in a string, where a segment is defined
to be a contiguous sequence of non-space characters. Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don't need to remove any of the intervals since Example 3:
they're already non-overlapping.
Input: [ [1,4], [2,3], [3,4] ]
Example 1: 10
/ \
Input: [ [1,2] ] 5 -3
/ \ \
Output: [-1] 3 2 11
/ \ \
Explanation: There is only one interval in the collection, so it 3 -2 1
outputs -1.
Return 3. The paths that sum to 8 are:
1. 5 -> 3
Example 2: 2. 5 -> 2 -> 1
3. -3 -> 11
Input: [ [3,4], [2,3], [1,2] ]
Input: ------------------------------
s: "cbaebabacd" p: "abc" ------------------------------
Arranging Coins
Output: ------------------------------
[0, 6] You have a total of n coins that you want to form in a staircase
shape, where every k-th row must have exactly k coins.
Explanation:
The substring with start index = 0 is "cba", which is an anagram of Given n, find the total number of full staircase rows that can be
"abc". formed.
The substring with start index = 6 is "bac", which is an anagram of
"abc". n is a non-negative integer and fits within the range of a 32-bit
signed integer.
Example 1:
Example 2:
n = 5
Input:
s: "abab" p: "ab" The coins can form the following rows:
¤
Output: ¤ ¤
[0, 1, 2] ¤ ¤
Example:
------------------------------
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) ------------------------------
Output: 7 -> 8 -> 0 -> 7 Number of Boomerangs
------------------------------
Given n points in the plane that are all pairwise distinct, a
------------------------------ "boomerang" is a tuple of points (i, j, k) such that the distance
------------------------------ between i and j equals the distance between i and k (the order of
Arithmetic Slices II - Subsequence the tuple matters).
------------------------------
A sequence of numbers is called arithmetic if it consists of at Find the number of boomerangs. You may assume that n will be at most
least three elements and if the difference between any two 500 and coordinates of points are all in the range [-10000, 10000]
consecutive elements is the same. (inclusive).
Find all the elements of [1, n] inclusive that do not appear in this Note: Time complexity should be O(height of tree).
array.
Example:
Could you do it without extra space and in O(n) runtime? You may
assume the returned list does not count as extra space. root = [5,3,6,2,4,null,7]
key = 3
Example:
5
Input: / \
[4,3,2,7,8,2,3,1] 3 6
/ \ \
Output: 2 4 7
[5,6]
Given key to delete is 3. So we find the node with value 3 and
delete it.
------------------------------
------------------------------ One valid answer is [5,4,6,2,null,null,7], shown in the following
Serialize and Deserialize BST BST.
------------------------------
Serialization is the process of converting a data structure or 5
object into a sequence of bits so that it can be stored in a file or / \
memory buffer, or transmitted across a network connection link to be 4 6
reconstructed later in the same or another computer environment. / \
2 7
Design an algorithm to serialize and deserialize a binary search
tree. There is no restriction on how your serialization/ Another valid answer is [5,2,6,null,4,null,7].
deserialization algorithm should work. You just need to ensure that
a binary search tree can be serialized to a string and this string 5
can be deserialized to the original tree structure. / \
2 6
\ \
The encoded string should be as compact as possible. 4 7
------------------------------
Note: Do not use class member/global/static variables to store ------------------------------
states. Your serialize and deserialize algorithms should be Sort Characters By Frequency
stateless. ------------------------------
Given a string, sort it in decreasing order based on the frequency
------------------------------ of characters.
------------------------------
Delete Node in a BST Example 1:
------------------------------
Input:
"tree" Output:
3
Output:
"eert" Explanation:
Only three moves are needed (remember each move increments two
Explanation: elements):
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
a valid answer.
------------------------------
------------------------------
Example 2: 4Sum II
------------------------------
Input: Given four lists A, B, C, D of integer values, compute how many
"cccaaa" tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is
zero.
Output:
"cccaaa" To make problem a bit easier, all A, B, C, D have same length of N
where 0 ≤ N ≤ 500. All integers are in the range of -228 to
Explanation: 228 - 1 and the result is guaranteed to be at most 231 - 1.
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid
answer. Example:
Note that "cacaca" is incorrect, as the same characters must be
together. Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
Example 3: D = [ 0, 2]
Input: Output:
"Aabb" 2
Output: Explanation:
"bbAa" The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 =
Explanation: 0
"bbaA" is also a valid answer, but "Aabb" is incorrect. 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 =
Note that 'A' and 'a' are treated as two different characters. 0
------------------------------ ------------------------------
------------------------------ ------------------------------
Minimum Moves to Equal Array Elements Assign Cookies
------------------------------ ------------------------------
Given a non-empty integer array of size n, find the minimum number
of moves required to make all array elements equal, where a move is Assume you are an awesome parent and want to give your children some
incrementing n - 1 elements by 1. cookies. But, you should give each child at most one cookie. Each
child i has a greed factor gi, which is the minimum size of a cookie
Example: that the child will be content with; and each cookie j has a size
sj. If sj >= gi, we can assign the cookie j to the child i, and the
Input: child i will be content. Your goal is to maximize the number of your
[1,2,3] content children and output the maximum number.
Note:
You may assume the greed factor is always positive. Example 2:
You cannot assign more than one cookie to one child.
Input: [3, 1, 4, 2]
Input: [1,2,3], [1,1] Explanation: There is a 132 pattern in the sequence: [1, 4, 2].
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of Example 3:
3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you Input: [-1, 3, 2, 0]
could only make the child whose greed factor is 1 content.
You need to output 1. Output: True
Input: [1, 2, 3, 4]
Example 3:
Output: False
Input: "abcabcabcabc"
Explanation: There is no 132 pattern in the sequence.
------------------------------ Input: x = 1, y = 4
------------------------------
LFU Cache Output: 2
------------------------------
Design and implement a data structure for Least Frequently Used Explanation:
(LFU) cache. It should support the following operations: get and 1 (0 0 0 1)
put. 4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are
get(key) - Get the value (will always be positive) of the key if the different.
key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already
present. When the cache reaches its capacity, it should invalidate ------------------------------
the least frequently used item before inserting a new item. For the ------------------------------
purpose of this problem, when there is a tie (i.e., two or more keys Minimum Moves to Equal Array Elements II
that have the same frequency), the least recently used key would be ------------------------------
evicted. Given a non-empty integer array, find the minimum number of moves
required to make all array elements equal, where a move is
incrementing a selected element by 1 or decrementing a selected
Follow up: element by 1.
Could you do both operations in O(1) time complexity?
You may assume the array's length is at most 10,000.
Example:
Example:
LFUCache cache = new LFUCache( 2 /* capacity */ );
Input:
cache.put(1, 1); [1,2,3]
cache.put(2, 2);
cache.get(1); // returns 1 Output:
cache.put(3, 3); // evicts key 2 2
cache.get(2); // returns -1 (not found)
cache.get(3); // returns 3. Explanation:
cache.put(4, 4); // evicts key 1. Only two moves are needed (remember each move increments or
cache.get(1); // returns -1 (not found) decrements one element):
cache.get(3); // returns 3
cache.get(4); // returns 4 [1,2,3] => [2,2,3] => [2,2,2]
------------------------------ ------------------------------
------------------------------ ------------------------------
Hamming Distance Island Perimeter
------------------------------ ------------------------------
The Hamming distance between two integers is the number of positions You are given a map in form of a two-dimensional integer grid where
at which the corresponding bits are different. 1 represents land and 0 represents water. Grid cells are connected
horizontally/vertically (not diagonally). The grid is completely
Given two integers x and y, calculate the Hamming distance. surrounded by water, and there is exactly one island (i.e., one or
more connected land cells). The island doesn't have "lakes" (water
inside that isn't connected to the water around the island). One The second player will win by choosing 10 and get a total = 11,
cell is a square with side length 1. The grid is rectangular, width which is >= desiredTotal.
and height don't exceed 100. Determine the perimeter of the island. Same with other integers chosen by the first player, the second
player will always win.
Example:
[[0,1,0,0], ------------------------------
[1,1,1,0], ------------------------------
[0,1,0,0], ------------------------------
[1,1,0,0]] Count The Repetitions
------------------------------
Answer: 16 Define S = [s,n] as the string S which consists of n connected
Explanation: The perimeter is the 16 yellow stripes in the image strings s. For example, ["abc", 3] ="abcabcabc".
below: On the other hand, we define that string s1 can be obtained from
string s2 if we can remove some characters from s2 such that it
becomes s1. For example, “abc” can be obtained from “abdbec” based
on our definition, but it can not be obtained from “acbbe”.
------------------------------ You are given two non-empty strings s1 and s2 (each at most 100
------------------------------ characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2
Can I Win ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and
------------------------------ S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be
In the "100 game," two players take turns adding, to a running obtained from S1.
total, any integer from 1..10. The player who first causes the
running total to reach or exceed 100 wins. Example:
What if we change the game so that players cannot re-use integers? Input:
s1="acb", n1=4
For example, two players might take turns drawing from a common pool s2="ab", n2=2
of numbers of 1..15 without replacement until they reach a total >=
100. Return:
2
Given an integer maxChoosableInteger and another integer
desiredTotal, determine if the first player to move can force a win,
assuming both players play optimally. ------------------------------
------------------------------
You can always assume that maxChoosableInteger will not be larger Unique Substrings in Wraparound String
than 20 and desiredTotal will not be larger than 300. ------------------------------
Consider the string s to be the infinite wraparound string of
"abcdefghijklmnopqrstuvwxyz", so s will look like this:
Example "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Input: Now we have another string p. Your job is to find out how many
maxChoosableInteger = 10 unique non-empty substrings of p are present in s. In particular,
desiredTotal = 11 your input is the string p and you need to output the number of
different non-empty substrings of p in the string s.
Output:
false Note: p consists of only lowercase English letters and the size of p
might be over 10000.
Explanation:
No matter which integer the first player choose, the first player Example 1:
will lose.
The first player can choose an integer from 1 up to 10. Input: "a"
If the first player choose 1, the second player can only choose Output: 1
integers from 2 up to 10.
Input: "cac"
Output: 2 Besides, extra leading zeros in the IPv6 is also invalid. For
Explanation: There are two substrings "a", "c" of string "cac" in example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is
the string s. invalid.
Example 3: Note:
You may assume there is no extra space or special characters in the
Input: "zab" input string.
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab",
"zab" of string "zab" in the string s. Example 1:
Input: "172.16.254.1"
------------------------------
------------------------------ Output: "IPv4"
Validate IP Address
------------------------------ Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: "256.256.256.256"
IPv6 addresses are represented as eight groups of four hexadecimal
digits, each group representing 16 bits. The groups are separated by Output: "Neither"
colons (":"). For example, the address
2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we Explanation: This is neither a IPv4 address nor a IPv6 address.
could omit some leading zeros among four hexadecimal digits and some
low-case characters in the address to upper-case ones, so
2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit ------------------------------
leading zeros and using upper cases). ------------------------------
------------------------------
------------------------------
Concatenated Words
------------------------------
Given a list of words (without duplicates), please write a program Example 2:
that returns all concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised Input: [3,3,3,3,4]
entirely of at least two shorter words in the given array. Output: false
Example: Explanation: You cannot find a way to form a square with all the
matchsticks.
Input:
["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat
","ratcatdogcat"]
Note:
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
The length sum of the given matchsticks is in the range of 0 to
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and 10^9.
"cats"; "dogcatsdog" can be concatenated by "dog", "cats" and The length of the given matchstick array will not exceed 15.
"dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and
"cat".
------------------------------
------------------------------
Ones and Zeroes
Note: ------------------------------
In the computer world, use restricted resource you have to generate
The number of elements of the given array will not exceed 10,000 maximum benefit is what we always want to pursue.
The length sum of elements in the given array will not exceed For now, suppose you are a dominator of m 0s and n 1s respectively.
600,000. On the other hand, there is an array with strings consisting of only
All the input string will only include lower case letters. 0s and 1s.
The returned elements order does not matter.
Now your task is to find the maximum number of strings that you can
------------------------------ form with given m 0s and n 1s. Each 0 and 1 can be used at most
------------------------------ once.
Matchsticks to Square
------------------------------
Remember the story of Little Match Girl? By now, you know exactly
what matchsticks the little match girl has, please find out a way Note:
you can make one square by using up all those matchsticks. You
should not break any stick, but you can link them up, and each The given numbers of 0s and 1s will both not exceed 100
matchstick must be used exactly one time. The size of given string array won't exceed 600.
Input: [1,1,2,2,2] Explanation: This are totally 4 strings can be formed by the using
Output: true of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
Explanation: You can form a square with length 2, one side of the
square came two sticks with length 1.
Example 2:
Note:
------------------------------
------------------------------ The given integer is guaranteed to fit within the range of a 32-bit
Heaters signed integer.
------------------------------ You could assume no leading zero bit in the integer’s binary
Winter is coming! Your first job during the contest is to design a representation.
standard heater with fixed warm radius to warm all the houses.
Note:
Numbers of houses and heaters you are given are non-negative and Example 2:
will not exceed 25000.
Positions of houses and heaters you are given are non-negative and Input: 1
will not exceed 10^9. Output: 0
As long as a house is in the heaters' warm radius range, it can be Explanation: The binary representation of 1 is 1 (no leading zero
warmed. bits), and its complement is 0. So you need to output 0.
All the heaters follow your radius standard and the warm radius will
the same.
------------------------------
------------------------------
Total Hamming Distance
Example 1: ------------------------------
The Hamming distance between two integers is the number of positions
Input: [1,2,3],[2] at which the corresponding bits are different.
Output: 1
Explanation: The only heater was placed in the position 2, and if we Now your job is to find the total Hamming distance between all pairs
use the radius 1 standard, then all the houses can be warmed. of the given numbers.
Example:
Example 2:
Input: 4, 14, 2
Input: [1,2,3,4],[1,4]
Output: 1 Output: 6
Explanation: The two heater was placed in the position 1 and 4. We
need to use radius 1 standard, then all the houses can be warmed. Explanation: In binary representation, the 4 is 0100, 14 is 1110,
and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
------------------------------ HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14,
------------------------------ 2) = 2 + 2 + 2 = 6.
The string S is magical because concatenating the number of
contiguous occurrences of characters '1' and '2' generates the
string S itself.
Note:
------------------------------
------------------------------
Sliding Window Median If we group the consecutive '1's and '2's in S, it will be:
------------------------------
Median is the middle value in an ordered integer list. If the size
of the list is even, there is no middle value. So the median is the 1 22 11 2 1 22 1 22 11 2 11 22 ......
mean of the two middle value.
Examples:
[2,3,4] , the median is 3 and the occurrences of '1's or '2's in each group are:
[2,3], the median is (2 + 3) / 2 = 2.5
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Given an integer N as input, return the number of '1's in the first
N number in the magical string S.
Window position Median
--------------- -----
[1 3 -1] -3 5 3 6 7 1 Note:
1 [3 -1 -3] 5 3 6 7 -1 N will not exceed 100,000.
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6 Example 1:
Input: 6
Therefore, return the median sliding window as [1,-1,-1,3,5,6]. Output: 3
Explanation: The first 6 elements of magical string S is "12211" and
Note: it contains three 1's, so return 3.
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for
non-empty array.
------------------------------ ------------------------------
------------------------------ ------------------------------
Magical String License Key Formatting
------------------------------ ------------------------------
Now you are given a string S, which represents a software license
A magical string S consists of only '1' and '2' and obeys the key which we would like to format. The string S is composed of
following rules: alphanumerical characters and dashes. The dashes split the
alphanumerical characters within the string into groups. (i.e. if
there are M dashes, the string is split into M+1 groups). The dashes
Input: S = "2-4A0r7-4k", K = 4
Explanation: The string S has been split into two parts, each part Input: "1000000000000000000"
has 4 characters. Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.
Example 2: Note:
Explanation: The string S has been split into three parts, each part
has 3 characters except the first part as it could be shorter as ------------------------------
said above. ------------------------------
------------------------------
Max Consecutive Ones
------------------------------
Note: Given a binary array, find the maximum number of consecutive 1s in
this array.
The length of string S will not exceed 12,000, and K is a positive
integer. Example 1:
String S consists only of alphanumerical characters (a-z and/or A-Z
and/or 0-9) and dashes(-). Input: [1,1,0,1,1,1]
String S is non-empty. Output: 3
Explanation: The first two digits or the last three digits are
consecutive 1s.
------------------------------ The maximum number of consecutive 1s is 3.
------------------------------
Smallest Good Base
------------------------------
For an integer n, we call k>=2 a good base of n, if all digits of n Note:
base k are 1.
Now given a string representing n, you should return the smallest The input array will only contain 0 and 1.
good base of n in string format. The length of input array is a positive integer and will not exceed
10,000 Think about Zuma Game. You have a row of balls on the table, colored
red(R), yellow(Y), blue(B), green(G), and white(W). You also have
several balls in your hand.
------------------------------
------------------------------ Each time, you may choose a ball in your hand, and insert it into
Predict the Winner the row (including the leftmost place and rightmost place). Then, if
------------------------------ there is a group of 3 or more balls in the same color touching,
Given an array of scores that are non-negative integers. Player 1 remove these balls. Keep doing this until no more balls can be
picks one of the numbers from either end of the array followed by removed.
the player 2 and then player 1 and so on. Each time a player picks a
number, that number will not be available for the next player. This Find the minimal balls you have to insert to remove all the balls on
continues until all the scores have been chosen. The player with the the table. If you cannot remove all the balls, output -1.
maximum score wins.
You are given a list of non-negative integers, a1, a2, ..., an, and
Example: a target, S. Now you have 2 symbols + and -. For each integer, you
should choose one from + and - as its new symbol.
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to Find out how many ways to assign symbols to make sum of integers
construct it are [1,4], [2,2], [4,1]. equal to target S.
But according to requirement 2, [1,4] is illegal; according to
requirement 3, [4,1] is not optimal compared to [2,2]. So the
length L is 2, and the width W is 2. Example 1:
There are 5 ways to assign symbols to make the sum of nums be target
3.
Note:
You may assume the length of given time series array won't exceed
Note: 10000.
You may assume the numbers in the Teemo's attacking time series and
The length of the given array is positive and will not exceed 20. his poisoning time duration per attacking are non-negative integers,
The sum of elements in the given array will not exceed 1000. which won't exceed 10,000,000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
------------------------------
------------------------------ ------------------------------
------------------------------ Next Greater Element I
Teemo Attacking ------------------------------
------------------------------
You are given two arrays (without duplicates) nums1 and nums2 where
In LLP world, there is a hero called Teemo and his attacking can nums1’s elements are subset of nums2. Find all the next greater
make his enemy Ashe be in poisoned condition. Now, given the Teemo's numbers for nums1's elements in the corresponding places of nums2.
attacking ascending time series towards Ashe and the poisoning time
duration per Teemo's attacking, you need to output the total time
that Ashe is in poisoned condition.
The Next Greater Number of a number x in nums1 is the first greater
number to its right in nums2. If it does not exist, output -1 for
You may assume that Teemo attacks at the very beginning of a this number.
specific time point, and makes Ashe be in poisoned condition
immediately.
Example 1:
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Input: [1,4], 2 Output: [-1,3,-1]
Output: 4 Explanation:
Explanation: At time point 1, Teemo starts attacking Ashe and makes For number 4 in the first array, you cannot find the next
Ashe be poisoned immediately. This poisoned status will last 2 greater number for it in the second array, so output -1.
seconds until the end of time point 2. And at time point 4, Teemo For number 1 in the first array, the next greater number for it
attacks Ashe again, and causes Ashe to be in poisoned status for in the second array is 3.
another 2 seconds. So you finally need to output 4. For number 2 in the first array, there is no next greater number
for it in the second array, so output -1.
Example 2: Example 2:
Example 1:
------------------------------ You may use one character in the keyboard more than once.
------------------------------ You may assume the input string will only contain letters of
Diagonal Traverse alphabet.
------------------------------
Input:
[ Assume a BST is defined as follows:
[ 1, 2, 3 ],
[ 4, 5, 6 ], The left subtree of a node contains only nodes with keys less than
[ 7, 8, 9 ] or equal to the node's key.
] The right subtree of a node contains only nodes with keys greater
Output: [1,2,4,7,5,3,6,8,9] than or equal to the node's key.
Explanation: Both the left and right subtrees must also be binary search trees.
------------------------------
------------------------------ ------------------------------
IPO ------------------------------
------------------------------ Next Greater Element II
------------------------------
Suppose LeetCode will start its IPO soon. In order to sell a good
price of its shares to Venture Capital, LeetCode would like to work Given a circular array (the next element of the last element is the
on some projects to increase its capital before the IPO. Since it first element of the array), print the Next Greater Number for every
has limited resources, it can only finish at most k distinct element. The Next Greater Number of a number x is the first greater
projects before the IPO. Help LeetCode design the best way to number to its traversing-order next in the array, which means you
maximize its total capital after finishing at most k distinct could search circularly to find its next greater number. If it
projects. doesn't exist, output -1 for this number.
Example 1:
You are given several projects. For each project i, it has a pure
profit Pi and a minimum capital of Ci is needed to start the Input: [1,2,1]
corresponding project. Initially, you have W capital. When you Output: [2,-1,2]
finish a project, you will obtain its pure profit and the profit Explanation: The first 1's next greater number is 2; The number 2
will be added to your total capital. can't find next greater number; The second 1's next greater number
needs to search circularly, which is also 2.
------------------------------
Example 1: ------------------------------
Base 7
Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1]. ------------------------------
Given an integer, return its base 7 string representation.
Output: 4
Example 1:
Explanation: Since your initial capital is 0, you can only start the
project indexed 0. Input: 100
After finishing it you will obtain profit 1 and your Output: "202"
capital becomes 1.
With capital 1, you can either start the project
indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to Example 2:
finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is Input: -7
0 + 1 + 3 = 4. Output: "-10"
Note: Note:
The input will be in range of [-1e7, 1e7].
------------------------------ Given the root of a tree, you are asked to find the most frequent
------------------------------ subtree sum. The subtree sum of a node is defined as the sum of all
------------------------------ the node values formed by the subtree rooted at that node (including
Relative Ranks the node itself). So what is the most frequent subtree sum value? If
------------------------------ there is a tie, return all the values with the highest frequency in
any order.
Given scores of N athletes, find their relative ranks and the people
with the top three highest scores, who will be awarded medals: "Gold
Medal", "Silver Medal" and "Bronze Medal". Examples 1
Input:
Example 1:
5
Input: [5, 4, 3, 2, 1] / \
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] 2 -3
Explanation: The first three athletes got the top three highest
scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". return [2, -3, 4], since all the values happen only once, return all
For the left two athletes, you just need to output their relative of them in any order.
ranks according to their scores.
Examples 2
Input:
Note:
5
N is a positive integer and won't exceed 10,000. / \
All the scores of athletes are guaranteed to be unique. 2 -5
Example: Given a binary tree, find the leftmost value in the last row of the
tree.
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14 Example 1:
Input:
Note: 2
The input number n will not exceed 100,000,000. (1e8) / \
1 3
------------------------------
------------------------------ Output:
Most Frequent Subtree Sum 1
------------------------------
step. After the pressing, you could begin to spell the next
character in the key (next stage), otherwise, you've finished all
Example 2: the spelling.
Input:
1
/ \ Example:
2 3
/ / \
4 5 6
/
7
Input: ring = "godding", key = "gd"
Output: Output: 4
7 Explanation: For the first key character 'g', since it is already in
place, we just need 1 step to spell this character. For the second
key character 'd', we need to rotate the ring "godding"
anticlockwise by two steps to make it become "ddinggo". Also, we
Note: need 1 more step for spelling. So the final output is 4.
You may assume the tree (i.e., the given root node) is not NULL.
------------------------------
------------------------------ Note:
Freedom Trail
------------------------------ Length of both ring and key will be in range 1 to 100.
There are only lowercase letters in both strings and might be some
In the video game Fallout 4, the quest "Road to Freedom" requires duplcate characters in both strings.
players to reach a metal dial called the "Freedom Trail Ring", and It's guaranteed that string key could always be spelled by rotating
use the dial to spell a specific keyword in order to open the door. the string ring.
------------------------------
Given a string ring, which represents the code engraved on the outer ------------------------------
ring and another string key, which represents the keyword needs to Find Largest Value in Each Tree Row
be spelled. You need to find the minimum number of steps in order to ------------------------------
spell all the characters in the keyword. You need to find the largest value in each row of a binary tree.
Input: [0,2,0]
Example 2:
Input: Output: -1
"cbbd" Explanation:
It's impossible to make all the three washing machines have the same
Output: number of dresses.
Explanation: Otherwise, we define that this word doesn't use capitals in a right
1st move: 1 0 <-- 5 => 1 1 4 way.
All the given strings' lengths will not exceed 10.
The length of the given list will be in the range of [2, 50].
Example 1:
Note: Example 1:
The input will be a non-empty word consisting of uppercase and
lowercase latin letters. Input: [23, 2, 4, 6, 7], k=6
Output: True
------------------------------ Explanation: Because [2, 4] is a continuous subarray of size 2 and
------------------------------ sums up to 6.
------------------------------
Longest Uncommon Subsequence II
------------------------------
Given a list of strings, you need to find the longest uncommon Example 2:
subsequence among them. The longest uncommon subsequence is defined
as the longest subsequence of one of these strings and this Input: [23, 2, 6, 4, 7], k=6
subsequence should not be any subsequence of the other strings. Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of
size 5 and sums up to 42.
Input: "aba", "cdc", "eae" Given a string and a string dictionary, find the longest string in
Output: 3 the dictionary that can be formed by deleting some characters of the
given string. If there are more than one possible results, return
the longest word with the smallest lexicographical order. If there
is no possible result, return the empty string.
Note:
Example 1: Note:
The length of the given binary array will not exceed 50,000.
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"] ------------------------------
------------------------------
Output: Beautiful Arrangement
"apple" ------------------------------
Output:
"a"
Note:
Example 1:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won't exceed 1,000. Input: 2
The length of all the strings in the input won't exceed 1,000. Output: 2
Explanation:
The first beautiful arrangement is [1, 2]:
------------------------------ Number at the 1st position (i=1) is 1, and 1 is divisible by i
------------------------------ (i=1).
Contiguous Array Number at the 2nd position (i=2) is 2, and 2 is divisible by i
------------------------------ (i=2).
Given a binary array, find the maximum length of a contiguous The second beautiful arrangement is [2, 1]:
subarray with equal number of 0 and 1. Number at the 1st position (i=1) is 2, and 2 is divisible by i
(i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by
Example 1: 1.
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal Note:
number of 0 and 1.
N is a positive integer and will not exceed 15.
Example 2: ------------------------------
------------------------------
Input: [0,1,0] ------------------------------
Output: 2 Minesweeper
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray ------------------------------
with equal number of 0 and 1. Let's play the minesweeper game (Wikipedia, online game)!
You are given a 2D char matrix representing the game board. 'M'
represents an unrevealed mine, 'E' represents an unrevealed empty
square, 'B' represents a revealed blank square that has no adjacent
(above, below, left, right, and all 4 diagonals) mines, digit ('1' Click : [1,2]
to '8') represents how many mines are adjacent to this revealed
square, and finally 'X' represents a revealed mine. Output:
Now given the next click position (row and column indices) among all [['B', '1', 'E', '1', 'B'],
the unrevealed squares ('M' or 'E'), return the board after ['B', '1', 'X', '1', 'B'],
revealing this position according to the following rules: ['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Explanation:
If a mine ('M') is revealed, then the game is over - change it to
'X'.
If an empty square ('E') with no adjacent mines is revealed, then
change it to revealed blank ('B') and all of its adjacent unrevealed
squares should be revealed recursively.
If an empty square ('E') with at least one adjacent mine is
revealed, then change it to a digit ('1' to '8') representing the Note:
number of adjacent mines.
Return the board when no more squares will be revealed. The range of the input matrix's height and width is [1,50].
The click position will only be an unrevealed square ('M' or 'E'),
which also means the input board contains at least one clickable
square.
Example 1: The input board won't be a stage when game is over (some mines have
been revealed).
Input: For simplicity, not mentioned rules should be ignored in this
problem. For example, you don't need to reveal all the unrevealed
[['E', 'E', 'E', 'E', 'E'], mines when the game is over, consider any cases that you will win
['E', 'E', 'M', 'E', 'E'], the game or flag any squares.
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
------------------------------
Click : [3,0] ------------------------------
Minimum Absolute Difference in BST
Output: ------------------------------
Given a binary search tree with non-negative values, find the
[['B', '1', 'E', '1', 'B'], minimum absolute difference between values of any two nodes.
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']] Example:
Explanation: Input:
1
\
3
Example 2: /
2
Input:
Output:
[['B', '1', 'E', '1', 'B'], 1
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'], Explanation:
['B', 'B', 'B', 'B', 'B']] The minimum absolute difference is 1, which is the difference
------------------------------
------------------------------
------------------------------
Note: Encode and Decode TinyURL
There are at least two nodes in this BST. ------------------------------
Note: This is a companion problem to the System Design problem:
------------------------------ Design TinyURL.
------------------------------
------------------------------ TinyURL is a URL shortening service where you enter a URL such as
K-diff Pairs in an Array https://leetcode.com/problems/design-tinyurl and it returns a short
------------------------------ URL such as http://tinyurl.com/4e9iAk.
Given an array of integers and an integer k, you need to find the Design the encode and decode methods for the TinyURL service. There
number of unique k-diff pairs in the array. Here a k-diff pair is is no restriction on how your encode/decode algorithm should work.
defined as an integer pair (i, j), where i and j are both numbers in You just need to ensure that a URL can be encoded to a tiny URL and
the array and their absolute difference is k. the tiny URL can be decoded to the original URL.
------------------------------
------------------------------
------------------------------
Example 1: Complex Number Multiplication
------------------------------
Input: [3, 1, 4, 1, 5], k = 2
Output: 2 Given two strings representing two complex numbers.
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3,
5).Although we have two 1s in the input, we should only return the
number of unique pairs. You need to return a string representing their multiplication. Note
i2 = -1 according to the definition.
Example 2: Example 1:
Example 3: Example 2:
Note:
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000. The input strings will not have extra blank.
All the integers in the given input belong to the range: [-1e7, The input strings will be given in the form of a+bi, where the
1e7]. integer a and b will both belong to the range of [-100, 100]. And
the output should be also in this form. string. If there are less than k characters left, reverse all of
them. If there are less than 2k but greater than or equal to k
characters, then reverse the first k characters and left the other
------------------------------ as original.
------------------------------
Convert BST to Greater Tree
------------------------------ Example:
Given a Binary Search Tree (BST), convert it to a Greater Tree such
that every key of the original BST is changed to the original key Input: s = "abcdefg", k = 2
plus sum of all keys greater than the original key in BST. Output: "bacdfeg"
Example:
Restrictions:
Input: The root of a Binary Search Tree like this:
5 The string consists of lower English letters only.
/ \ Length of the given string and k will in the range [1, 10000]
2 13
------------------------------
Output: The root of a Greater Tree like this: ------------------------------
18 01 Matrix
/ \ ------------------------------
20 13
Given a matrix consists of 0 and 1, find the distance of the nearest
0 for each cell.
------------------------------
------------------------------ The distance between two adjacent cells is 1.
Minimum Time Difference
------------------------------ Example 1:
Given a list of 24-hour clock time points in "Hour:Minutes" format, Input:
find the minimum minutes difference between any two time points in
the list. 0 0 0
0 1 0
Example 1: 0 0 0
The number of time points in the given list is at least 2 and won't
exceed 20000. Example 2:
The input time is legal and ranges from 00:00 to 23:59. Input:
0 0 0
------------------------------ 0 1 0
------------------------------ 1 1 1
Reverse String II
------------------------------ Output:
Example 1:
Note: Input:
The number of elements of the given matrix will not exceed 10,000. [1, 3, 2, 2, 2, 3, 4, 3, 1]
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and Output:
right.
23
------------------------------ Explanation:
------------------------------
Diameter of Binary Tree [1, 3, 2, 2, 2, 3, 4, 3, 1]
------------------------------ ----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
----> [1, 3, 3, 3, 1] (1*1=1 points)
Given a binary tree, you need to compute the length of the diameter ----> [1, 1] (3*3=9 points)
of the tree. The diameter of a binary tree is the length of the ----> [] (2*2=4 points)
longest path between any two nodes in a tree. This path may or may
not pass through the root.
Note:
The number of boxes n would not exceed 100.
Example:
Given a binary tree ------------------------------
------------------------------
1 Friend Circles
/ \ ------------------------------
2 3
/ \ There are N students in a class. Some of them are friends, while
4 5 some are not. Their friendship is transitive in nature. For example,
if A is a direct friend of B, and B is a direct friend of C, then A
is an indirect friend of C. And we defined a friend circle is a
group of students who are direct or indirect friends.
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Requirements: ------------------------------
------------------------------
For instance, "http://tinyurl.com/4e9iAk" is the tiny url for the License Key Formatting
page "https://leetcode.com/problems/design-tinyurl". The identifier ------------------------------
(the highlighted part) can be any string with 6 alphanumeric Now you are given a string S, which represents a software license
characters containing 0-9, a-z, A-Z. key which we would like to format. The string S is composed of
alphanumerical characters and dashes. The dashes split the
Each shortened URL must be unique; that is, no two different URLs alphanumerical characters within the string into groups. (i.e. if
can be shortened to the same URL. there are M dashes, the string is split into M+1 groups). The dashes
in the given string are possibly misplaced.
possibly the first group, which could be shorter, but still must subdir2
contain at least one character). To satisfy this requirement, we file.ext
will reinsert dashes. Additionally, all the lower case letters in
the string must be converted to upper case.
The directory dir contains an empty sub-directory subdir1 and a sub-
So, you are given a non-empty string S, representing a license key directory subdir2 containing a file file.ext.
to format, and an integer K. And you need to return the license key
formatted according to the description above. The string
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsu
bdir2\n\t\t\tfile2.ext" represents:
Example 1:
dir
Input: S = "2-4A0r7-4k", K = 4 subdir1
file1.ext
Output: "24A0-R74K" subsubdir1
subdir2
Explanation: The string S has been split into two parts, each part subsubdir2
has 4 characters. file2.ext
Design the encode and decode methods for the TinyURL service. There There are 1000 buckets, one and only one of them contains poison,
is no restriction on how your encode/decode algorithm should work. the rest are filled with water. They all look the same. If a pig
You just need to ensure that a URL can be encoded to a tiny URL and drinks that poison it will die within 15 minutes. What is the
the tiny URL can be decoded to the original URL. minimum amount of pigs you need to figure out which bucket contains
------------------------------ the poison within one hour.
------------------------------
Coin Change 2
------------------------------ Answer this question, and write an algorithm for the follow-up
general case.
You are given coins of different denominations and a total amount of
money. Write a function to compute the number of combinations that
make up that amount. You may assume that you have infinite number of
each kind of coin. Follow-up:
Note:
You can assume that If there are n buckets and a pig drinking poison will die within m
minutes, how many pigs (x) you need to figure out the "poison"
0 <= amount <= 5000 bucket within p minutes? There is exact one bucket with poison.
1 <= coin <= 5000
the number of coins is less than 500 ------------------------------
the answer is guaranteed to fit into signed 32-bit integer ------------------------------
Minimum Genetic Mutation
------------------------------
A gene string can be represented by an 8-character long string, with
Example 1: choices from "A", "C", "G", "T".
Input: amount = 5, coins = [1, 2, 5] Suppose we need to investigate about a mutation (mutation from
Output: 4 "start" to "end"), where ONE mutation is defined as ONE single
Explanation: there are four ways to make up the amount: character changed in the gene string.
5=5
5=2+2+1 For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
5=2+1+1+1
5=1+1+1+1+1 Also, there is a given gene "bank", which records all the valid gene
mutations. A gene must be in the bank to make it a valid gene
string.
Example 2:
Now, given 3 things - start, end, bank, your task is to determine
Input: amount = 3, coins = [2] what is the minimum number of mutations needed to mutate from
Output: 0 "start" to "end". If there is no such a mutation, return -1.
Explanation: the amount of 3 cannot be made up just with coins of 2.
Note:
------------------------------
------------------------------ Output:
------------------------------
LFU Cache 4
------------------------------
Design and implement a data structure for Least Frequently Used One possible longest palindromic subsequence is "bbbb".
(LFU) cache. It should support the following operations: get and
put.
Example 2:
Input:
get(key) - Get the value (will always be positive) of the key if the "cbbd"
key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already Output:
present. When the cache reaches its capacity, it should invalidate
the least frequently used item before inserting a new item. For the 2
purpose of this problem, when there is a tie (i.e., two or more keys
that have the same frequency), the least recently used key would be One possible longest palindromic subsequence is "bb".
evicted.
Follow up:
Could you do both operations in O(1) time complexity?
Example: