Output Leetcode Questions PDF
Output Leetcode Questions PDF
------------------------------
Single Element in a Sorted Array
------------------------------
Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,10,11,11]
Output: 10
Note:
Your solution should run in O(log n) time and O(1) space.
------------------------------
------------------------------
Coin Change 2
------------------------------
Note:
You can assume that
Example 1:
Example 2:
Example 3:
------------------------------
------------------------------
Largest Palindrome Product
------------------------------
Find the largest palindrome made from the product of two n-digit
numbers.
Since the result could be very large, you should return the largest
palindrome mod 1337.
Example:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Note:
The range of n is [1,8].
------------------------------
------------------------------
Find All Duplicates in an Array
------------------------------
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
------------------------------
------------------------------
Two Sum
------------------------------
Given an array of integers, return indices of the two numbers such
that they add up to a specific target.
You may assume that each input would have exactly one solution, and
you may not use the same element twice.
Example:
------------------------------
------------------------------
Add Two Numbers
------------------------------
You are given two non-empty linked lists representing two non-
negative integers. The digits are stored in reverse order and each
of their nodes contain a single digit. Add the two numbers and
return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Examples:
Given "pwwkew", the answer is "wke", with the length of 3. Note that
the answer must be a substring, "pwke" is a subsequence and not a
substring.
------------------------------
------------------------------
Median of Two Sorted Arrays
------------------------------
There are two sorted arrays nums1 and nums2 of size m and n
respectively.
Find the median of the two sorted arrays. The overall run time
complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
------------------------------
------------------------------
Longest Palindromic Substring
------------------------------
Given a string s, find the longest palindromic substring in s. You
may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Example:
Input: "cbbd"
Output: "bb"
------------------------------
------------------------------
ZigZag Conversion
------------------------------
P A H N
A P L S I I G
Y I R
Write the code that will take a string and make this conversion
given a number of rows:
------------------------------
------------------------------
Reverse Integer
------------------------------
Reverse digits of an integer.
Here are some good questions to ask before coding. Bonus points for
you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie,
cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the
input is a 32-bit integer, then the reverse of 1000000003 overflows.
How should you handle such cases?
For the purpose of this problem, assume that your function returns 0
when the reversed integer overflows.
Note:
The input is assumed to be a 32-bit signed integer. Your function
should return 0 when the reversed integer overflows.
------------------------------
------------------------------
String to Integer (atoi)
------------------------------
Implement atoi to convert a string to an integer.
Notes:
It is intended for this problem to be specified vaguely (ie, no
given input specs). You are responsible to gather all the input
requirements up front.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see
your function signature accepts a const char * argument, please
click the reload button to reset your code definition.
The string can contain additional characters after those that form
the integral number, which are ignored and have no effect on the
behavior of this function.
------------------------------
------------------------------
Palindrome Number
------------------------------
Determine whether an integer is a palindrome. Do this without extra
space.
Some hints:
You could also try reversing an integer. However, if you have solved
the problem "Reverse Integer", you know that the reversed integer
might overflow. How would you handle such case?
------------------------------
------------------------------
Regular Expression Matching
------------------------------
Implement regular expression matching with support for '.' and '*'.
The matching should cover the entire input string (not partial).
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
------------------------------
------------------------------
Container With Most Water
------------------------------
Given n non-negative integers a1, a2, ..., an, where each represents
a point at coordinate (i, ai). n vertical lines are drawn such that
the two endpoints of line i is at (i, ai) and (i, 0). Find two
lines, which together with x-axis forms a container, such that the
container contains the most water.
Note: You may not slant the container and n is at least 2.
------------------------------
------------------------------
Integer to Roman
------------------------------
Given an integer, convert it to a roman numeral.
------------------------------
------------------------------
3Sum
------------------------------
Given an array S of n integers, are there elements a, b, c in S such
that a + b + c = 0? Find all unique triplets in the array which
gives the sum of zero.
------------------------------
------------------------------
3Sum Closest
------------------------------
Given an array S of n integers, find three integers in S such that
the sum is closest to a given number, target. Return the sum of the
three integers. You may assume that each input would have exactly
one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
------------------------------
------------------------------
Letter Combinations of a Phone Number
------------------------------
Given a digit string, return all possible letter combinations that
the number could represent.
Note:
Although the above answer is in lexicographical order, your answer
could be in any order you want.
------------------------------
------------------------------
4Sum
------------------------------
Given an array S of n integers, are there elements a, b, c, and d in
S such that a + b + c + d = target? Find all unique quadruplets in
the array which gives the sum of target.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
------------------------------
------------------------------
Remove Nth Node From End of List
------------------------------
Given a linked list, remove the nth node from the end of list and
return its head.
For example,
After removing the second node from the end, the linked list
becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
------------------------------
------------------------------
Valid Parentheses
------------------------------
Given a string containing just the characters '(', ')', '{', '}',
'[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are
all valid but "(]" and "([)]" are not.
------------------------------
------------------------------
Merge Two Sorted Lists
------------------------------
Merge two sorted linked lists and return it as a new list. The new
list should be made by splicing together the nodes of the first two
lists.
------------------------------
------------------------------
Generate Parentheses
------------------------------
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
------------------------------
------------------------------
Merge k Sorted Lists
------------------------------
------------------------------
------------------------------
Swap Nodes in Pairs
------------------------------
Given a linked list, swap every two adjacent nodes and return its
head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify
the values in the list, only nodes itself can be changed.
------------------------------
------------------------------
Reverse Nodes in k-Group
------------------------------
You may not alter the values in the nodes, only nodes itself may be
changed.
For example,
Given this linked list: 1->2->3->4->5
------------------------------
------------------------------
Remove Duplicates from Sorted Array
------------------------------
Given a sorted array, remove the duplicates in place such that each
element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in
place with constant memory.
For example,
Given input array nums = [1,1,2],
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
beyond the new length.
------------------------------
------------------------------
Remove Element
------------------------------
Given an array and a value, remove all instances of that value in
place and return the new length.
Do not allocate extra space for another array, you must do this in
place with constant memory.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements
of nums being 2.
------------------------------
------------------------------
Implement strStr()
------------------------------
Implement strStr().
------------------------------
------------------------------
Divide Two Integers
------------------------------
------------------------------
------------------------------
Substring with Concatenation of All Words
------------------------------
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
that is a concatenation of each word in words exactly once and
without any intervening characters.
------------------------------
------------------------------
Next Permutation
------------------------------
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
3,2,1 → 1,2,3
1,1,5 → 1,5,1
------------------------------
------------------------------
Longest Valid Parentheses
------------------------------
Given a string containing just the characters '(' and ')', find the
length of the longest valid (well-formed) parentheses substring.
------------------------------
------------------------------
Search in Rotated Sorted Array
------------------------------
Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.
You are given a target value to search. If found in the array return
its index, otherwise return -1.
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
------------------------------
------------------------------
Search Insert Position
------------------------------
Given a sorted array and a target value, return the index if the
target is found. If not, return the index where it would be if it
were inserted in order.
------------------------------
------------------------------
Valid Sudoku
------------------------------
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The
Rules.
The Sudoku board could be partially filled, where empty cells are
filled with the character '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable.
Only the filled cells need to be validated.
------------------------------
------------------------------
Sudoku Solver
------------------------------
Write a program to solve a Sudoku puzzle by filling the empty cells.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
------------------------------
------------------------------
Count and Say
------------------------------
The count-and-say sequence is the sequence of integers beginning as
follows:
1, 11, 21, 1211, 111221, ...
------------------------------
------------------------------
Combination Sum
------------------------------
Note:
[
[7],
[2, 2, 3]
]
------------------------------
------------------------------
Combination Sum II
------------------------------
Note:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
------------------------------
------------------------------
First Missing Positive
------------------------------
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
------------------------------
------------------------------
Trapping Rain Water
------------------------------
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
Note:
------------------------------
------------------------------
Wildcard Matching
------------------------------
Implement wildcard pattern matching with support for '?' and '*'.
The matching should cover the entire input string (not partial).
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
------------------------------
------------------------------
Jump Game II
------------------------------
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
Note:
You can assume that you can always reach the last index.
------------------------------
------------------------------
Permutations
------------------------------
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
------------------------------
------------------------------
Permutations II
------------------------------
For example,
[1,1,2] have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
------------------------------
------------------------------
Rotate Image
------------------------------
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
------------------------------
------------------------------
Group Anagrams
------------------------------
Given an array of strings, group anagrams together.
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
------------------------------
------------------------------
N-Queens II
------------------------------
Follow up for N-Queens problem.
------------------------------
------------------------------
Maximum Subarray
------------------------------
More practice:
If you have figured out the O(n) solution, try coding another
solution using the divide and conquer approach, which is more
subtle.
------------------------------
------------------------------
Spiral Matrix
------------------------------
Given a matrix of m x n elements (m rows, n columns), return all
elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
------------------------------
------------------------------
Jump Game
------------------------------
For example:
A = [2,3,1,1,4], return true.
------------------------------
------------------------------
Merge Intervals
------------------------------
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
------------------------------
------------------------------
Insert Interval
------------------------------
Given a set of non-overlapping intervals, insert a new interval into
the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to
their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],
[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as
[1,2],[3,10],[12,16].
------------------------------
------------------------------
Length of Last Word
------------------------------
Given a string s consists of upper/lower-case alphabets and empty
space characters ' ', return the length of last word in the string.
For example,
Given s = "Hello World",
return 5.
------------------------------
------------------------------
Spiral Matrix II
------------------------------
Given an integer n, generate a square matrix filled with elements
from 1 to n2 in spiral order.
For example,
Given n = 3,
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
------------------------------
------------------------------
Permutation Sequence
------------------------------
The set [1,2,3,…,n] contains a total of n! unique
permutations.
"123"
"132"
"213"
"231"
"312"
"321"
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
------------------------------
------------------------------
Unique Paths
------------------------------
A robot is located at the top-left corner of a m x n grid (marked
'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid
(marked 'Finish' in the diagram below).
Now consider if some obstacles are added to the grids. How many
unique paths would there be?
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated
below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Note: You can only move either down or right at any point in time.
------------------------------
------------------------------
Valid Number
------------------------------
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see
your function signature accepts a const char * argument, please
click the reload button to reset your code definition.
------------------------------
------------------------------
Plus One
------------------------------
Given a non-negative integer represented as a non-empty array of
digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except
the number 0 itself.
The digits are stored such that the most significant digit is at the
head of the list.
------------------------------
------------------------------
Add Binary
------------------------------
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
------------------------------
------------------------------
Text Justification
------------------------------
Given an array of words and a length L, format the text such that
each line has exactly L characters and is fully (left and right)
justified.
You should pack your words in a greedy approach; that is, pack as
many words as you can in each line. Pad extra spaces ' ' when
necessary so that each line has exactly L characters.
For the last line of text, it should be left justified and no extra
space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text",
"justification."]
L: 16.
[
"This is an",
"example of text",
"justification. "
]
Corner Cases:
A line other than the last line might contain only one word. What
should you do in this case?
In this case, that line should be left-justified.
------------------------------
------------------------------
Sqrt(x)
------------------------------
Implement int sqrt(int x).
Each time you can either climb 1 or 2 steps. In how many distinct
ways can you climb to the top?
------------------------------
------------------------------
Simplify Path
------------------------------
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
------------------------------
------------------------------
Edit Distance
------------------------------
Given two words word1 and word2, find the minimum number of steps
required to convert word1 to word2. (each operation is counted as 1
step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
------------------------------
------------------------------
Set Matrix Zeroes
------------------------------
Follow up:
------------------------------
------------------------------
Search a 2D Matrix
------------------------------
Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:
For example,
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given an array with n objects colored red, white or blue, sort them
so that objects of the same color are adjacent, with the colors in
the order red, white and blue.
Note:
You are not suppose to use the library's sort function for this
problem.
Follow up:
A rather straight forward solution is a two-pass algorithm using
counting sort.
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
2's.
Could you come up with an one-pass algorithm using only constant
space?
------------------------------
------------------------------
Minimum Window Substring
------------------------------
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T,
return the empty string "".
If there are multiple such windows, you are guaranteed that there
will always be only one unique minimum window in S.
------------------------------
------------------------------
Combinations
------------------------------
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
------------------------------
------------------------------
Subsets
------------------------------
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
------------------------------
------------------------------
Word Search
------------------------------
Given a 2D board and a word, find if the word exists in the grid.
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
------------------------------
------------------------------
Remove Duplicates from Sorted Array II
------------------------------
For example,
Given sorted array nums = [1,1,1,2,2,3],
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.
------------------------------
------------------------------
Search in Rotated Sorted Array II
------------------------------
Given a sorted linked list, delete all nodes that have duplicate
numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
------------------------------
------------------------------
Remove Duplicates from Sorted List
------------------------------
Given a sorted linked list, delete all duplicates such that each
element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
------------------------------
------------------------------
Largest Rectangle in Histogram
------------------------------
The largest rectangle is shown in the shaded area, which has area =
10 unit.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
------------------------------
------------------------------
Maximal Rectangle
------------------------------
Given a 2D binary matrix filled with 0's and 1's, find the largest
rectangle containing only 1's and return its area.
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
------------------------------
------------------------------
Partition List
------------------------------
Given a linked list and a value x, partition it such that all nodes
less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each
of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
------------------------------
------------------------------
Scramble String
------------------------------
Given a string s1, we may represent it as a binary tree by
partitioning it to two non-empty substrings recursively.
great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its
two children.
For example, if we choose the node "gr" and swap its two children,
it produces a scrambled string "rgeat".
rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
------------------------------
------------------------------
Merge Sorted Array
------------------------------
Given two sorted integer arrays nums1 and nums2, merge nums2 into
nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or
equal to m + n) to hold additional elements from nums2. The number
of elements initialized in nums1 and nums2 are m and n respectively.
------------------------------
------------------------------
Gray Code
------------------------------
The gray code is a binary numeral system where two successive values
differ in only one bit.
00 - 0
01 - 1
11 - 3
10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For now, the judge is able to judge based on one instance of gray
code sequence. Sorry about that.
------------------------------
------------------------------
Subsets II
------------------------------
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
------------------------------
------------------------------
Decode Ways
------------------------------
'A' -> 1
'B' -> 2
...
'Z' -> 26
For example,
Given encoded message "12",
it could be decoded as "AB" (1 2) or "L" (12).
------------------------------
------------------------------
Reverse Linked List II
------------------------------
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
------------------------------
------------------------------
Restore IP Addresses
------------------------------
Given a string containing only digits, restore it by returning all
possible valid IP address combinations.
For example:
Given "25525511135",
------------------------------
------------------------------
Binary Tree Inorder Traversal
------------------------------
Given a binary tree, return the inorder traversal of its nodes'
values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
------------------------------
------------------------------
Unique Binary Search Trees
------------------------------
Given n, how many structurally unique BST's (binary search trees)
that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
------------------------------
------------------------------
Interleaving String
------------------------------
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
------------------------------
------------------------------
Validate Binary Search Tree
------------------------------
The left subtree of a node contains only nodes with keys less than
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.
Example 1:
2
/ \
1 3
Example 2:
1
/ \
2 3
------------------------------
------------------------------
Recover Binary Search Tree
------------------------------
Note:
A solution using O(n) space is pretty straight forward. Could you
devise a constant space solution?
------------------------------
------------------------------
Same Tree
------------------------------
Given two binary trees, write a function to check if they are equal
or not.
------------------------------
------------------------------
Symmetric Tree
------------------------------
Given a binary tree, check whether it is a mirror of itself (ie,
symmetric around its center).
1
/ \
2 2
/ \ / \
3 4 4 3
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
------------------------------
------------------------------
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).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
------------------------------
------------------------------
Binary Tree Zigzag Level Order Traversal
------------------------------
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
next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
[
[3],
[20,9],
[15,7]
]
------------------------------
------------------------------
Maximum Depth of Binary Tree
------------------------------
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from
the root node down to the farthest leaf node.
------------------------------
------------------------------
Construct Binary Tree from Preorder and Inorder Traversal
------------------------------
Given preorder and inorder traversal of a tree, construct the binary
tree.
Note:
You may assume that duplicates do not exist in the tree.
------------------------------
------------------------------
Construct Binary Tree from Inorder and Postorder Traversal
------------------------------
Given inorder and postorder traversal of a tree, construct the
binary tree.
Note:
You may assume that duplicates do not exist in the tree.
------------------------------
------------------------------
Binary Tree Level Order Traversal II
------------------------------
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
to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
[
[15,7],
[9,20],
[3]
]
------------------------------
------------------------------
Convert Sorted Array to Binary Search Tree
------------------------------
Given an array where elements are sorted in ascending order, convert
it to a height balanced BST.
------------------------------
------------------------------
Convert Sorted List to Binary Search Tree
------------------------------
Given a singly linked list where elements are sorted in ascending
order, convert it to a height balanced BST.
------------------------------
------------------------------
Balanced Binary Tree
------------------------------
Given a binary tree, determine if it is height-balanced.
------------------------------
------------------------------
Minimum Depth of Binary Tree
------------------------------
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path
from the root node down to the nearest leaf node.
------------------------------
------------------------------
Path Sum
------------------------------
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
the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
Given a binary tree and a sum, find all root-to-leaf paths where
each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
------------------------------
------------------------------
Flatten Binary Tree to Linked List
------------------------------
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
1
\
2
\
3
\
4
\
5
\
6
Hints:
If you notice carefully in the flattened tree, each node's right
child points to the next node of a pre-order traversal.
------------------------------
------------------------------
Distinct Subsequences
------------------------------
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
------------------------------
------------------------------
Populating Next Right Pointers in Each Node
------------------------------
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
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.
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
1 -> NULL
\ /
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
------------------------------
------------------------------
Populating Next Right Pointers in Each Node II
------------------------------
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous
solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
------------------------------
------------------------------
Pascal's Triangle
------------------------------
Given numRows, generate the first numRows of Pascal's triangle.
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
------------------------------
------------------------------
Pascal's Triangle II
------------------------------
Given an index k, return the kth row of the Pascal's triangle.
Note:
Could you optimize your algorithm to use only O(k) extra space?
------------------------------
------------------------------
Triangle
------------------------------
Given a triangle, find the minimum path sum from top to bottom. Each
step you may move to adjacent numbers on the row below.
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
Note:
Bonus point if you are able to do this using only O(n) extra space,
where n is the total number of rows in the triangle.
------------------------------
------------------------------
Best Time to Buy and Sell Stock
------------------------------
Say you have an array for which the ith element is the price of a
given stock on day i.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
------------------------------
------------------------------
Best Time to Buy and Sell Stock II
------------------------------
Say you have an array for which the ith element is the price of a
given stock on day i.
Note:
You may not engage in multiple transactions at the same time (ie,
you must sell the stock before you buy again).
------------------------------
------------------------------
Binary Tree Maximum Path Sum
------------------------------
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
------------------------------
------------------------------
Valid Palindrome
------------------------------
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good
question to ask during an interview.
------------------------------
------------------------------
Word Ladder II
------------------------------
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
------------------------------
------------------------------
Word Ladder
------------------------------
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -
> "cog",
return its length 5.
Note:
UPDATE (2017/1/20):
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.
------------------------------
------------------------------
Longest Consecutive Sequence
------------------------------
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return
its length: 4.
------------------------------
------------------------------
Sum Root to Leaf Numbers
------------------------------
Given a binary tree containing digits from 0-9 only, each root-to-
leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the
number 123.
For example,
1
/ \
2 3
------------------------------
------------------------------
Surrounded Regions
------------------------------
Given a 2D board containing 'X' and 'O' (the letter O), capture all
regions surrounded by 'X'.
X X X X
X O O X
X X O X
X O X X
X X X X
X X X X
X X X X
X O X X
------------------------------
------------------------------
Palindrome Partitioning
------------------------------
Return
[
["aa","b"],
["a","a","b"]
]
------------------------------
------------------------------
Palindrome Partitioning II
------------------------------
------------------------------
------------------------------
Clone Graph
------------------------------
The graph has a total of three nodes, and therefore contains three
parts as separated by #.
1
/ \
/ \
0 --- 2
/ \
\_/
------------------------------
------------------------------
Gas Station
------------------------------
There are N gas stations along a circular route, where the amount of
gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of
gas to travel from station i to its next station (i+1). You begin
the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the
circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
------------------------------
------------------------------
Candy
------------------------------
------------------------------
------------------------------
Single Number
------------------------------
Given an array of integers, every element appears twice except for
one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory?
------------------------------
------------------------------
Single Number II
------------------------------
Note:
Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory?
------------------------------
------------------------------
Copy List with Random Pointer
------------------------------
------------------------------
------------------------------
Word Break
------------------------------
UPDATE (2017/1/4):
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.
------------------------------
------------------------------
Word Break II
------------------------------
UPDATE (2017/1/4):
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.
------------------------------
------------------------------
Linked List Cycle
------------------------------
Follow up:
Can you solve it without using extra space?
------------------------------
------------------------------
Linked List Cycle II
------------------------------
Given a linked list, return the node where the cycle begins. If
there is no cycle, return null.
------------------------------
------------------------------
Reorder List
------------------------------
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
------------------------------
------------------------------
Binary Tree Preorder Traversal
------------------------------
Given a binary tree, return the preorder traversal of its nodes'
values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Design and implement a data structure for Least Recently Used (LRU)
cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the
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 reached its capacity, it should invalidate
the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
------------------------------
------------------------------
Insertion Sort List
------------------------------
Sort a linked list using insertion sort.
------------------------------
------------------------------
Sort List
------------------------------
Sort a linked list in O(n log n) time using constant space
complexity.
------------------------------
------------------------------
Max Points on a Line
------------------------------
Given n points on a 2D plane, find the maximum number of points that
lie on the same straight line.
------------------------------
------------------------------
Evaluate Reverse Polish Notation
------------------------------
Some examples:
------------------------------
------------------------------
Reverse Words in a String
------------------------------
For example,
Given s = "the sky is blue",
return "blue is sky the".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
What constitutes a word?
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
trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
------------------------------
------------------------------
Maximum Product Subarray
------------------------------
------------------------------
------------------------------
Find Minimum in Rotated Sorted Array
------------------------------
Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.
Design a stack that supports push, pop, top, and retrieving the
minimum element in constant time.
Example:
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
Intersection of Two Linked Lists
------------------------------
Write a program to find the node at which the intersection of two
singly linked lists begins.
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
Notes:
The array may contain multiple peaks, in that case return the index
to any one of the peaks is fine.
Note:
Your solution should be in logarithmic complexity.
You may assume all elements in the array are non-negative integers
and fit in the 32-bit signed integer range.
You may assume that the version strings are non-empty and contain
only digits and the . character.
The . character does not represent a decimal point and is used to
separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version
three", it is the fifth second-level revision of the second first-
level revision.
For example,
The function twoSum should return indices of the two numbers such
that they add up to the target, where index1 must be less than
index2. Please note that your returned answers (both index1 and
index2) are not zero-based.
You may assume that each input would have exactly one solution and
you may not use the same element twice.
------------------------------
------------------------------
Excel Sheet Column Title
------------------------------
Given a positive integer, return its corresponding column title as
appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
You may assume that the array is non-empty and the majority element
always exist in the array.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses
O(h) memory, where h is the height of the tree.
The demons had captured the princess (P) and imprisoned her in the
bottom-right corner of a dungeon. The dungeon consists of M x N
rooms laid out in a 2D grid. Our valiant knight (K) was initially
positioned in the top-left room and must fight his way through the
dungeon to rescue the princess.
The knight has an initial health point represented by a positive
integer. If at any point his health point drops to 0 or below, he
dies immediately.
Some of the rooms are guarded by demons, so the knight loses health
(negative integers) upon entering these rooms;
other rooms are either empty (0's) or contain magic orbs that
increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight
decides to move only rightward or downward in each step.
-2 (K)
-3
3
-5
-10
1
10
30
-5 (P)
Notes:
For example, given [3, 30, 34, 5, 9], the largest formed number is
9534330.
Note: The result may be very large, so you need to return a string
instead of an integer.
For example,
Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",
Return:
["AAAAACCCCC", "CCCCCAAAAA"].
------------------------------
------------------------------
Best Time to Buy and Sell Stock IV
------------------------------
Say you have an array for which the ith element is the price of a
given stock on day i.
Note:
You may not engage in multiple transactions at the same time (ie,
you must sell the stock before you buy again).
Note:
Try to come up as many solutions as you can, there are at least 3
different ways to solve this problem.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Follow up:
If this function is called many times, how would you optimize it?
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
For example, given the range [5, 7], you should return 4.
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
------------------------------
------------------------------
Isomorphic Strings
------------------------------
Given two strings s and t, determine if they are isomorphic.
For example,
Given "egg", "add", return true.
Note:
You may assume both s and t have the same length.
------------------------------
------------------------------
Reverse Linked List
------------------------------
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively.
Could you implement both?
------------------------------
------------------------------
Course Schedule
------------------------------
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.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should
have finished course 0, and to take course 0 you should also have
finished course 1. So it is impossible.
Note:
Hints:
Note:
You may assume that all inputs are consist of lowercase letters a-z.
------------------------------
------------------------------
Minimum Size Subarray Sum
------------------------------
More practice:
If you have figured out the O(n) solution, try coding another
solution of which the time complexity is O(n log n).
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 the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
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].
Note:
Hints:
------------------------------
------------------------------
Add and Search Word - Data structure design
------------------------------
void addWord(word)
bool search(word)
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
You should be familiar with how a Trie works. If not, please work on
this problem: Implement Trie (Prefix Tree) first.
------------------------------
------------------------------
Word Search II
------------------------------
Given a 2D board and a list of words from the dictionary, find all
words in the board.
For example,
Given words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Return ["eat","oath"].
Note:
You may assume that all inputs are consist of lowercase letters a-z.
If the current candidate does not exist in all words' prefix, you
could stop backtracking immediately. What kind of data structure
could answer such query efficiently? Does a hash table work? Why or
why not? How about a Trie? If you would like to learn how to
implement a basic trie, please work on this problem: Implement Trie
(Prefix Tree) first.
------------------------------
------------------------------
House Robber II
------------------------------
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found
himself a new place for his thievery so that he will not get too
much attention. This time, all houses at this place are arranged in
a circle. That means the first house is the neighbor of the last
one. Meanwhile, the security system for these houses remain the same
as for those in the previous street.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
------------------------------
------------------------------
The Skyline Problem
------------------------------
A city's skyline is the outer contour of the silhouette formed by
all the buildings in that city when viewed from a distance. Now
suppose you are given the locations and height of all the buildings
as shown on a cityscape photo (Figure A), write a program to output
the skyline formed by these buildings collectively (Figure B).
Notes:
------------------------------
------------------------------
Contains Duplicate III
------------------------------
Given an array of integers, find out whether there are two distinct
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.
------------------------------
------------------------------
Maximal Square
------------------------------
Given a 2D binary matrix filled with 0's and 1's, find the largest
square containing only 1's and return its area.
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
Assume that the total area is never beyond the maximum possible
value of int.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
------------------------------
------------------------------
Implement Stack using Queues
------------------------------
Notes:
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.
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.
You may assume that all operations are valid (for example, no pop or
top operations will be called on an empty stack).
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
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.
------------------------------
------------------------------
Basic Calculator II
------------------------------
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -,
*, / operators and empty spaces . The integer division should
truncate toward zero.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
------------------------------
------------------------------
Kth Smallest Element in a BST
------------------------------
Given a binary search tree, write a function kthSmallest to find the
kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Follow up:
What if the BST is modified (insert/delete operations) often and you
need to find the kth smallest frequently? How would you optimize the
kthSmallest routine?
Notes:
You must use only standard operations of a stack -- which means only
push to top, peek/pop from top, size, and is empty operations are
valid.
Depending on your language, stack may not be supported natively. You
may simulate a stack by using a list or deque (double-ended queue),
as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or
peek operations will be called on an empty queue).
------------------------------
------------------------------
Number of Digit One
------------------------------
Given an integer n, count the total number of digit 1 appearing in
all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10,
11, 12, 13.
Beware of overflow.
------------------------------
------------------------------
Palindrome Linked List
------------------------------
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
------------------------------
------------------------------
Lowest Common Ancestor of a Binary Search Tree
------------------------------
Given a binary search tree (BST), find the lowest common ancestor
(LCA) of two given nodes in the BST.
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6.
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.
------------------------------
------------------------------
Lowest Common Ancestor of a Binary Tree
------------------------------
Given a binary tree, find the lowest common ancestor (LCA) of two
given nodes in the tree.
_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the
third node with value 3, the linked list should become 1 -> 2 -> 4
after calling your function.
------------------------------
------------------------------
Product of Array Except Self
------------------------------
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
elements of nums except nums[i].
Follow up:
Could you solve it with constant space complexity? (Note: The output
array does not count as extra space for the purpose of space
complexity analysis.)
------------------------------
------------------------------
Sliding Window Maximum
------------------------------
Given an array nums, there is a sliding window of size k which is
moving from the very left of the array to the very right. You can
only see the k numbers in the window. Each time the sliding window
moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for
non-empty array.
Follow up:
Could you solve it in linear time?
------------------------------
------------------------------
Search a 2D Matrix II
------------------------------
Write an efficient algorithm that searches for a value in an m x n
matrix. This matrix has the following properties:
For example,
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt
your solution to such case?
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
Binary Tree Paths
------------------------------
1
/ \
2 3
\
5
For example:
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
For example:
Note:
The order of the result is not important. So in the above example,
[5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you
implement it using only constant space complexity?
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it
includes another prime factor 7.
Ugly numbers are positive numbers whose prime factors only include
2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence
of the first 10 ugly numbers.
The naive approach is to call isUgly for every number until you
reach the nth one. Most numbers are not ugly. Try to focus your
effort on generating only the ugly ones.
An ugly number must be multiplied by either 2, 3, or 5 from a
smaller ugly number.
The key is how to maintain the order of the ugly numbers. Try a
similar approach of merging from three sorted lists: L1, L2, and L3.
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1
* 2, L2 * 3, L3 * 5).
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you
implement it using only constant extra space complexity?
For example,
Did you see a pattern in dividing the number into chunk of words?
For example, 123 and 123000.
Group the number by thousands (3 digits). You can write a helper
function that takes a number less than 1000 and convert just that
chunk to words.
There are many edge cases. What are some good test cases? Does
your code work with input such as 0? Or 1000010? (middle chunk is
zero and should not be printed out)
------------------------------
------------------------------
H-Index
------------------------------
Note: If there are several possible values for h, the maximum one is
taken as the h-index.
------------------------------
------------------------------
------------------------------
------------------------------
First Bad Version
------------------------------
Suppose you have n versions [1, 2, ..., n] and you want to find out
the first bad one, which causes all the following ones to be bad.
Given a string that contains only digits 0-9 and a target value,
return all possibilities to add binary operators (not unary) +, -,
or * between the digits so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []
Given an array nums, write a function to move all 0's to the end of
it while maintaining the relative order of the non-zero elements.
Note:
Now you call peek() and it returns 2, the next element. Calling
next() after that still return 2.
You call next() the final time and it returns 3, the last element.
Calling hasNext() after that should return false.
Follow up: How would you extend your design to be generic and work
with all types, not just integer?
Note:
You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be
repeated more than once.
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
(horizontal, vertical, diagonal) using the following four rules
(taken from the above Wikipedia article):
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
generation.
Any live cell with more than three live neighbors dies, as if by
over-population..
Any dead cell with exactly three live neighbors becomes a live cell,
as if by reproduction.
Write a function to compute the next state (after one update) of the
board given its current state.
Follow up:
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
You may assume pattern contains only lowercase letters, and str
contains lowercase letters separated by a single space.
You are playing the following Nim Game with your friend: There is a
heap of stones on the table, each time one of you take turns to
remove 1 to 3 stones. The one who removes the last stone will be the
winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the
game. Write a function to determine whether you can win the game
given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never
win the game: no matter 1, 2, or 3 stones you remove, the last stone
will always be removed by your friend.
If there are 5 stones in the heap, could you figure out a way to
remove the stones such that you will always be the winner?
void addNum(int num) - Add a integer number from the data stream to
the data structure.
double findMedian() - Return the median of all elements so far.
For example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
1
/ \
2 3
/ \
4 5
For example:
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
Please note that both secret number and friend's guess may contain
duplicate digits, for example:
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd
1 is a cow, and your function should return "1A1B".
You may assume that the secret number and your friend's guess only
contain digits, and their lengths are always equal.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
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.
Note: The input string may contain letters other than the
parentheses ( and ).
Examples:
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
------------------------------
------------------------------
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
right corner (row2, col2).
The above rectangle (with the red border) is defined by (row1, col1)
= (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
Note:
------------------------------
------------------------------
------------------------------
Additive Number
------------------------------
Additive number is a string whose digits can form additive sequence.
For example:
"112358" is an additive number because the digits can form an
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
Follow up:
How would you handle overflow for very large input integers?
Example:
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function
is distributed evenly.
------------------------------
------------------------------
------------------------------
Minimum Height Trees
------------------------------
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
(each edge is a pair of labels).
You can assume that no duplicate edges will appear in edges. Since
all edges are
undirected, [0, 1] is the same as [1, 0] and thus will not
appear together in
edges.
Example 1:
0
|
1
/ \
2 3
return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
return [3, 4]
Note:
You are asked to burst all the balloons. If the you burst
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
then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons
wisely.
Note:
(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
Example:
Given [3, 1, 5, 8]
Return 167
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]
is the sequence of the first 12 super ugly numbers given primes
= [2, 7, 13, 19] of size 4.
Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(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.
------------------------------
------------------------------
------------------------------
Count of Smaller Numbers After Self
------------------------------
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:
------------------------------
------------------------------
Remove Duplicate Letters
------------------------------
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
Example 1:
Example 2:
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
toggle every third bulb (turning on if it's off or turning off if
it's on). For the ith round, you toggle every i bulb. For the nth
round, you only toggle the last bulb.
Given n = 3.
At first, the three bulbs are [off, off, off].
After first round, the three bulbs are [on, on, on].
After second round, the three bulbs are [on, off, on].
After third round, the three bulbs are [on, off, off].
So you should return 1, because there is only one bulb is on.
------------------------------
------------------------------
------------------------------
Create Maximum Number
------------------------------
Example 1:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]
Example 2:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]
Example 3:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
return [9, 8, 9]
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of
coin.
Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1,
4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2,
3, 1, 3, 1, 2].
Note:
You may assume all input has valid answer.
Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra
space?
Follow up:
Could you do it without using any loop / recursion?
Note:
A naive algorithm of O(n2) is trivial. You MUST do better than
that.
Example:
Given nums = [-2, 5, -1], lower = -2, upper = 2,
Return 3.
The three ranges are : [0, 0], [2, 2], [0, 2] and their
respective sums are: -2, -1, 2.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain
as it was in the input.
The first node is considered odd, the second node even and so on ...
From each cell, you can either move to four directions: left, right,
up or down. You may NOT move diagonally or move outside of the
boundary (i.e. wrap-around is not allowed).
Example 1:
nums = [
[9,9,4],
[6,6,8],
[2,1,1]
]
Return 4
Example 2:
nums = [
[3,4,5],
[3,2,6],
[2,2,1]
]
Return 4
Example 1:
nums = [1, 3], n = 6
Return 1.
Combinations of nums are [1], [3], [1,3], which form possible sums
of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3],
[1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1,
6].
So we only need 1 patch.
Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].
Example 3:
nums = [1, 2, 2], n = 5
Return 0.
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
For example, the above binary tree can be serialized to the string
"9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.
You may assume that the input format is always valid, for example it
could never contain two consecutive commas such as "1,,3".
Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true
Example 2:
"1,#"
Return false
Example 3:
"9,#,#,1"
Return false
Note:
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"],
["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],
["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is
["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical
order.
Your algorithm should run in O(n) time complexity and O(1) space
complexity.
Examples:
Given [1, 2, 3, 4, 5],
return true.
Example 1:
Example 2:
Example 3:
Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
The thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root." Besides
the root, each house has one and only one parent house. After a
tour, the smart thief realized that "all houses in this place forms
a binary tree". It will automatically contact the police if two
directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight
without alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
Example 1:
Given the list [[1,1],2,[1,1]],
Example 2:
Given the list [1,[4,[6]]],
------------------------------
------------------------------
Power of Four
------------------------------
Example:
Given num = 16, return true.
Given num = 5, return false.
Note: You may assume that n is not less than 2 and not larger than
58.
Example:
Given s = "hello", return "olleh".
------------------------------
------------------------------
Reverse Vowels of a String
------------------------------
Write a function that takes a string as input and reverse only the
vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
------------------------------
------------------------------
------------------------------
Top K Frequent Elements
------------------------------
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
------------------------------
------------------------------
------------------------------
Intersection of Two Arrays
------------------------------
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
------------------------------
------------------------------
Intersection of Two Arrays II
------------------------------
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
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
algorithm is better?
What if elements of nums2 are stored on disk, and the memory is
limited such that you cannot load all elements into the memory at
once?
------------------------------
------------------------------
------------------------------
Data Stream as Disjoint Intervals
------------------------------
Given a data stream input of non-negative integers a1, a2, ...,
an, ..., summarize the numbers seen so far as a list of disjoint
intervals.
For example, suppose the integers from the data stream are 1, 3, 7,
2, 6, ..., then the summary will be:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
Follow up:
What if there are lots of merges and the number of disjoint
intervals are small compared to the data stream's size?
What is the maximum number of envelopes can you Russian doll? (put
one inside other)
Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of
envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
------------------------------
------------------------------
Design Twitter
------------------------------
Design a simplified version of Twitter where users can post tweets,
follow/unfollow another user and is able to see the 10 most recent
tweets in the user's news feed. Your design should support the
following methods:
Example:
// User 1's news feed should return a list with 1 tweet id -> [5].
twitter.getNewsFeed(1);
// User 1's news feed should return a list with 2 tweet ids -> [6,
5].
// Tweet id 6 should precede tweet id 5 because it is posted after
tweet id 5.
twitter.getNewsFeed(1);
// User 1's news feed should return a list with 1 tweet id -> [5],
// since user 1 is no longer following user 2.
twitter.getNewsFeed(1);
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
------------------------------
Max Sum of Rectangle No Larger Than K
------------------------------
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:
Given matrix = [
[1, 0, 1],
[0, -2, 3]
]
k = 2
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).
Note:
Operations allowed:
Input: x = 3, y = 5, z = 4
Output: True
Example 2:
Input: x = 2, y = 6, z = 5
Output: False
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Example 1:
nums: [1,2,3]
Example 2:
nums: [1,2,4,8]
Result: [1,2,4,8]
Example:
Given a = 1 and b = 2, return 3.
Example1:
a = 2
b = [3]
Result: 8
Example2:
a = 2
b = [1,0]
Result: 1024
You are given two integer arrays nums1 and nums2 sorted in ascending
order and an integer k.
Define a pair (u,v) which consists of one element from the first
array and one element from the second array.
Example 1:
Return: [1,2],[1,4],[1,6]
Example 2:
Return: [1,1],[1,1]
Return: [1,3],[2,3]
Every time you guess wrong, I'll tell you whether the number is
higher or lower.
-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example:
n = 10, I pick 6.
Return 6.
------------------------------
------------------------------
Guess Number Higher or Lower II
------------------------------
We are playing the Guess Game. The game is as follows:
Every time you guess wrong, I'll tell you whether the number I
picked is higher or lower.
However, when you guess a particular number x, and you guess wrong,
you pay $x. You win the game when you guess the number I picked.
Example:
n = 10, I pick 8.
First round: You guess 5, I tell you that it's higher. You pay $5.
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.
Given a particular n ≥ 1, find out how much money you need to
have to guarantee a win.
Examples:
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is
[1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
Follow up:
Can you do it in O(n) time?
Example:
nums = [1, 2, 3]
target = 4
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative
numbers?
Note that it is the kth smallest element in the sorted order, not
the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
------------------------------
------------------------------
------------------------------
Insert Delete GetRandom O(1)
------------------------------
Design a data structure that supports all following operations in
average O(1) time.
Example:
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
------------------------------
------------------------------
Insert Delete GetRandom O(1) - Duplicates allowed
------------------------------
Design a data structure that supports all following operations in
average O(1) time.
Note: Duplicate elements are allowed.
Example:
------------------------------
------------------------------
Linked List Random Node
------------------------------
Given a singly linked list, return a random node's value from the
linked list. Each node must have the same probability of being
chosen.
Follow up:
What if the linked list is extremely large and its length is unknown
to you? Could you solve this efficiently without using extra space?
Example:
------------------------------
------------------------------
Ransom Note
------------------------------
Note:
You may assume that both strings contain only lowercase letters.
------------------------------
------------------------------
Shuffle an Array
------------------------------
Shuffle a set of numbers without duplicates.
Example:
// Shuffle the array [1,2,3] and return its result. Any permutation
of [1,2,3] must equally likely to be returned.
solution.shuffle();
------------------------------
------------------------------
Mini Parser
------------------------------
Given a nested list of integers represented as a string, implement a
parser to deserialize it.
Note:
You may assume that the string is well-formed:
String is non-empty.
String does not contain white spaces.
String contains only digits 0-9, [, - ,, ].
Example 1:
Given s = "324",
Example 2:
Given s = "[123,[456,[789]]]",
------------------------------
------------------------------
Lexicographical Numbers
------------------------------
Please optimize your algorithm to use less time and space. The input
size may be as large as 5,000,000.
------------------------------
------------------------------
First Unique Character in a String
------------------------------
Examples:
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
------------------------------
------------------------------
Longest Absolute File Path
------------------------------
Suppose we abstract our file system by a string in the following
manner:
dir
subdir1
subdir2
file.ext
The string
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsu
bdir2\n\t\t\tfile2.ext" represents:
dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
------------------------------
------------------------------
Elimination Game
------------------------------
Repeat the previous step again, but this time from right to left,
remove the right most number and every other number from the
remaining numbers.
Find the last number that remains starting with a list of length n.
Example:
Input:
n = 9,
1 2 3 4 5 6 7 8 9
2 4 6 8
2 6
6
Output:
6
------------------------------
------------------------------
Perfect Rectangle
------------------------------
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false. Because two of the rectangles overlap with each other.
------------------------------
------------------------------
Is Subsequence
------------------------------
You may assume that there is only lower case English letters in both
s and t. t is potentially a very long (length ~= 500,000) string,
and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the
original string by deleting some (can be none) of the characters
without disturbing the relative positions of the remaining
characters. (ie, "ace" is a subsequence of "abcde" while "aec" is
not).
Example 1:
s = "abc", t = "ahbgdc"
Return true.
Example 2:
s = "axc", t = "ahbgdc"
Return false.
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B,
and you want to check one by one to see if T has its subsequence. In
this scenario, how would you change your code?
Note:
The input is an array of integers. Only the least significant 8 bits
of each integer is used to store the data. This means each integer
represents only 1 byte of data.
Example 1:
data = [197, 130, 1], which represents the octet sequence: 11000101
10000010 00000001.
Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a
1-byte character.
Example 2:
data = [235, 140, 4], which represented the octet sequence: 11101011
10001100 00000100.
Return false.
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
correct.
But the second continuation byte does not start with 10, so it is
invalid.
------------------------------
------------------------------
Decode String
------------------------------
You may assume that the input string is always valid; No extra white
spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain
any digits and that digits are only for those repeat numbers, k. For
example, there won't be input like 3a or 2[4].
Examples:
------------------------------
------------------------------
Longest Substring with At Least K Repeating Characters
------------------------------
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
------------------------------
------------------------------
Rotate Function
------------------------------
Note:
n is guaranteed to be less than 105.
Example:
A = [4, 3, 2, 6]
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
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
------------------------------
------------------------------
Integer Replacement
------------------------------
Example 1:
Input:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1
Example 2:
Input:
7
Output:
4
Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1
------------------------------
------------------------------
Random Pick Index
------------------------------
Note:
The array size can be very large. Solution that uses too much extra
space will not pass the judge.
Example:
------------------------------
------------------------------
Evaluate Division
------------------------------
Example:
Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a
= ?, a / e = ?, a / a = ?, x / x = ? . return [6.0, 0.5, -1.0,
1.0, -1.0 ].
The input is always valid. You may assume that evaluating the
queries will result in no division by zero and there is no
contradiction.
------------------------------
------------------------------
Nth Digit
------------------------------
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed
integer (n < 231).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, ... is a 0, which is part of the number 10.
------------------------------
------------------------------
Binary Watch
------------------------------
A binary watch has 4 LEDs on the top which represent the hours
(0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on
the right.
Example:
Input: n = 1Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02",
"0:04", "0:08", "0:16", "0:32"]
Note:
------------------------------
------------------------------
Remove K Digits
------------------------------
Given a non-negative integer num represented as a string, remove k
digits from the number so that the new number is the smallest
possible.
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.
Example 1:
Example 2:
Example 3:
------------------------------
------------------------------
Frog Jump
------------------------------
A frog is crossing a river. The river is divided into x units and at
each unit there may or may not exist a stone. The frog can jump on a
stone, but it must not jump into the water.
If the frog's last jump was k units, then its next jump must be
either k - 1, k, or k + 1 units. Note that the frog can only jump in
the forward direction.
Note:
Example 1:
[0,1,3,5,6,8,12,17]
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,
4 units to the 7th stone, and 5 units to the 8th stone.
Example 2:
[0,1,2,3,4,8,9,11]
------------------------------
------------------------------
Sum of Left Leaves
------------------------------
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15
respectively. Return 24.
------------------------------
------------------------------
Convert a Number to Hexadecimal
------------------------------
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
------------------------------
------------------------------
Queue Reconstruction by Height
------------------------------
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
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
algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
Example
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
------------------------------
------------------------------
Trapping Rain Water II
------------------------------
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
it is able to trap after raining.
Note:
Both m and n are less than 110. The height of each unit cell is
greater than 0 and is less than 20,000.
Example:
Return 4.
After the rain, water are trapped between the blocks. The total
volume of water trapped is 4.
------------------------------
------------------------------
------------------------------
Longest Palindrome
------------------------------
Given a string which consists of lowercase or uppercase letters,
find the length of the longest palindromes that can be built with
those letters.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length
is 7.
------------------------------
------------------------------
Split Array Largest Sum
------------------------------
Given an array which consists of non-negative integers and an
integer m, you can split the array into m non-empty continuous
subarrays. Write an algorithm to minimize the largest sum among
these m subarrays.
Note:
If n is the length of array, assume the following constraints are
satisfied:
Examples:
Input:
nums = [7,2,5,10,8]
m = 2
Output:
18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.
------------------------------
------------------------------
------------------------------
Fizz Buzz
------------------------------
Write a program that outputs the string representation of numbers
from 1 to n.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
------------------------------
------------------------------
Arithmetic Slices
------------------------------
A sequence of number is called arithmetic if it consists of at least
three elements and if the difference between any two consecutive
elements is the same.
Example:
A = [1, 2, 3, 4]
------------------------------
------------------------------
Third Maximum Number
------------------------------
Given a non-empty array of integers, return the third maximum number
in this array. If it does not exist, return the maximum number. The
time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is
returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third
maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
------------------------------
------------------------------
Add Strings
------------------------------
Given two non-negative integers num1 and num2 represented as string,
return the sum of num1 and num2.
Note:
------------------------------
------------------------------
Partition Equal Subset Sum
------------------------------
Given a non-empty array containing only positive integers, find if
the array can be partitioned into two subsets such that the sum of
elements in both subsets is equal.
Note:
Example 1:
Output: true
Example 2:
Input: [1, 2, 3, 5]
Output: false
------------------------------
------------------------------
Pacific Atlantic Water Flow
------------------------------
Given an m x n matrix of non-negative integers representing the
height of each unit cell in a continent, the "Pacific ocean" touches
the left and top edges of the matrix and the "Atlantic ocean"
touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right)
from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the
Pacific and Atlantic ocean.
Note:
Example:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions
with parentheses in above matrix).
------------------------------
------------------------------
------------------------------
Battleships in a Board
------------------------------
Given an 2D board, count how many battleships are in it. The
battleships are represented with 'X's, empty slots are represented
with '.'s. You may assume the following rules:
Example:
X..X
...X
...X
Invalid Example:
...X
XXXX
...X
Example:
Output: 28
Explanation: The maximum result is 5 ^ 25 = 28.
------------------------------
------------------------------
------------------------------
Reconstruct Original Digits from English
------------------------------
Given a non-empty string containing an out-of-order English
representation of digits 0-9, output the digits in ascending order.
Note:
Example 1:
Input: "owoztneoer"
Output: "012"
Example 2:
Input: "fviefuro"
Output: "45"
------------------------------
------------------------------
Longest Repeating Character Replacement
------------------------------
Given a string that consists of only uppercase English letters, you
can replace any letter in the string with another letter at most k
times. Find the length of a longest substring containing all
repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 104.
Example 1:
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace the two 'A's with two 'B's or vice versa.
Example 2:
Input:
s = "AABABBA", k = 1
Output:
4
Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
------------------------------
------------------------------
------------------------------
All O`one Data Structure
------------------------------
Implement a data structure supporting the following operations:
------------------------------
------------------------------
Number of Segments in a String
------------------------------
Count the number of segments in a string, where a segment is defined
to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable
characters.
Example:
------------------------------
------------------------------
Non-overlapping Intervals
------------------------------
Note:
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.
Example 1:
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-
overlapping.
Example 2:
Output: 2
Example 3:
------------------------------
------------------------------
Find Right Interval
------------------------------
For any interval i, you need to store the minimum interval j's
index, which means that the interval j has the minimum start point
to build the "right" relationship for interval i. If the interval j
doesn't exist, store -1 for the interval i. Finally, you need output
the stored value of each interval as an array.
Note:
You may assume the interval's end point is always bigger than its
start point.
You may assume none of these intervals have the same start point.
Example 1:
Input: [ [1,2] ]
Output: [-1]
Example 2:
Output: [-1, 0, 1]
------------------------------
------------------------------
Path Sum III
------------------------------
You are given a binary tree in which each node contains an integer
value.
The path does not need to start or end at the root or a leaf, but it
must go downwards
(traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the
range -1,000,000 to 1,000,000.
Example:
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
------------------------------
------------------------------
Find All Anagrams in a String
------------------------------
Given a string s and a non-empty string p, find all the start
indices of p's anagrams in s.
Example 1:
Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of
"abc".
The substring with start index = 6 is "bac", which is an anagram of
"abc".
Example 2:
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of
"ab".
The substring with start index = 1 is "ba", which is an anagram of
"ab".
The substring with start index = 2 is "ab", which is an anagram of
"ab".
------------------------------
------------------------------
------------------------------
K-th Smallest in Lexicographical Order
------------------------------
Given integers n and k, find the lexicographically k-th smallest
integer in the range from 1 to n.
Example:
Input:
n: 13 k: 2
Output:
10
Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7,
8, 9], so the second smallest number is 10.
------------------------------
------------------------------
Arranging Coins
------------------------------
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.
Given n, find the total number of full staircase rows that can be
formed.
Example 1:
n = 5
Example 2:
n = 8
------------------------------
------------------------------
Find All Duplicates in an Array
------------------------------
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
------------------------------
------------------------------
------------------------------
Add Two Numbers II
------------------------------
You are given two non-empty linked lists representing two non-
negative integers. The most significant digit comes first and each
of their nodes contain a single digit. Add the two numbers and
return it as a linked list.
You may assume the two numbers do not contain any leading zero,
except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing
the lists is not allowed.
Example:
------------------------------
------------------------------
Arithmetic Slices II - Subsequence
------------------------------
A sequence of numbers is called arithmetic if it consists of at
least three elements and if the difference between any two
consecutive elements is the same.
Example:
Output: 7
Explanation:
All arithmetic subsequence slices are:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
------------------------------
------------------------------
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
the tuple matters).
Find the number of boomerangs. You may assume that n will be at most
500 and coordinates of points are all in the range [-10000, 10000]
(inclusive).
Example:
Input:
[[0,0],[1,0],[2,0]]
Output:
2
Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
------------------------------
------------------------------
Find All Numbers Disappeared in an Array
------------------------------
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this
array.
Could you do it without extra space and in O(n) runtime? You may
assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
------------------------------
------------------------------
Serialize and Deserialize BST
------------------------------
Serialization is the process of converting a data structure or
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
reconstructed later in the same or another computer environment.
------------------------------
------------------------------
Delete Node in a BST
------------------------------
Given a root node reference of a BST and a key, delete the node with
the given key in the BST. Return the root node reference (possibly
updated) of the BST.
Example:
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
5
/ \
4 6
/ \
2 7
5
/ \
2 6
\ \
4 7
------------------------------
------------------------------
Sort Characters By Frequency
------------------------------
Given a string, sort it in decreasing order based on the frequency
of characters.
Example 1:
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also
a valid answer.
Example 2:
Input:
"cccaaa"
Output:
"cccaaa"
Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid
answer.
Note that "cacaca" is incorrect, as the same characters must be
together.
Example 3:
Input:
"Aabb"
Output:
"bbAa"
Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
------------------------------
------------------------------
Minimum Moves to Equal Array Elements
------------------------------
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
incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two
elements):
------------------------------
------------------------------
4Sum II
------------------------------
Given four lists A, B, C, D of integer values, compute how many
tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is
zero.
Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
Output:
2
Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 =
0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 =
0
------------------------------
------------------------------
Assign Cookies
------------------------------
Assume you are an awesome parent and want to give your children some
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
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
child i will be content. Your goal is to maximize the number of your
content children and output the maximum number.
Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.
Example 1:
Output: 1
Example 2:
Output: 2
------------------------------
------------------------------
132 Pattern
------------------------------
Example 1:
Input: [1, 2, 3, 4]
Output: False
Input: [3, 1, 4, 2]
Output: True
Example 3:
Input: [-1, 3, 2, 0]
Output: True
------------------------------
------------------------------
Repeated Substring Pattern
------------------------------
Given a non-empty string check if it can be constructed by taking a
substring of it and appending multiple copies of the substring
together. You may assume the given string consists of lowercase
English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring
"abcabc" twice.)
------------------------------
------------------------------
LFU Cache
------------------------------
Design and implement a data structure for Least Frequently Used
(LFU) cache. It should support the following operations: get and
put.
get(key) - Get the value (will always be positive) of the key if the
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
that have the same frequency), the least recently used key would be
evicted.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.get(3); // returns 3.
cache.put(4, 4); // evicts key 1.
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
------------------------------
------------------------------
Hamming Distance
------------------------------
The Hamming distance between two integers is the number of positions
at which the corresponding bits are different.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are
different.
------------------------------
------------------------------
Minimum Moves to Equal Array Elements II
------------------------------
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
element by 1.
Example:
Input:
[1,2,3]
Output:
2
Explanation:
Only two moves are needed (remember each move increments or
decrements one element):
------------------------------
------------------------------
Island Perimeter
------------------------------
You are given a map in form of a two-dimensional integer grid where
1 represents land and 0 represents water. Grid cells are connected
horizontally/vertically (not diagonally). The grid is completely
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
cell is a square with side length 1. The grid is rectangular, width
and height don't exceed 100. Determine the perimeter of the island.
Example:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Answer: 16
Explanation: The perimeter is the 16 yellow stripes in the image
below:
------------------------------
------------------------------
Can I Win
------------------------------
In the "100 game," two players take turns adding, to a running
total, any integer from 1..10. The player who first causes the
running total to reach or exceed 100 wins.
For example, two players might take turns drawing from a common pool
of numbers of 1..15 without replacement until they reach a total >=
100.
Example
Input:
maxChoosableInteger = 10
desiredTotal = 11
Output:
false
Explanation:
No matter which integer the first player choose, the first player
will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose
integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11,
which is >= desiredTotal.
Same with other integers chosen by the first player, the second
player will always win.
------------------------------
------------------------------
------------------------------
Count The Repetitions
------------------------------
Define S = [s,n] as the string S which consists of n connected
strings s. For example, ["abc", 3] ="abcabcabc".
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
≤ 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
obtained from S1.
Example:
Input:
s1="acb", n1=4
s2="ab", n2=2
Return:
2
------------------------------
------------------------------
Unique Substrings in Wraparound String
------------------------------
Consider the string s to be the infinite wraparound string of
"abcdefghijklmnopqrstuvwxyz", so s will look like this:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
Now we have another string p. Your job is to find out how many
unique non-empty substrings of p are present in s. In particular,
your input is the string p and you need to output the number of
different non-empty substrings of p in the string s.
Example 1:
Input: "a"
Output: 1
Explanation: Only the substring "a" of string "a" is in the string
s.
Example 2:
Input: "cac"
Output: 2
Explanation: There are two substrings "a", "c" of string "cac" in
the string s.
Example 3:
Input: "zab"
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab",
"zab" of string "zab" in the string s.
------------------------------
------------------------------
Validate IP Address
------------------------------
Note:
You may assume there is no extra space or special characters in the
input string.
Example 1:
Input: "172.16.254.1"
Output: "IPv4"
Example 2:
Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Example 3:
Input: "256.256.256.256"
Output: "Neither"
------------------------------
------------------------------
------------------------------
------------------------------
Concatenated Words
------------------------------
Given a list of words (without duplicates), please write a program
that returns all concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised
entirely of at least two shorter words in the given array.
Example:
Input:
["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat
","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Note:
The number of elements of the given array will not exceed 10,000
The length sum of elements in the given array will not exceed
600,000.
All the input string will only include lower case letters.
The returned elements order does not matter.
------------------------------
------------------------------
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
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
matchstick must be used exactly one time.
Example 1:
Input: [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the
square came two sticks with length 1.
Example 2:
Input: [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the
matchsticks.
Note:
------------------------------
------------------------------
Ones and Zeroes
------------------------------
In the computer world, use restricted resource you have to generate
maximum benefit is what we always want to pursue.
For now, suppose you are a dominator of m 0s and n 1s respectively.
On the other hand, there is an array with strings consisting of only
0s and 1s.
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.
Note:
Example 1:
Example 2:
Input: Array = {"10", "0", "1"}, m = 1, n = 1
Output: 2
Explanation: You could form "10", but then you'd have nothing left.
Better form "0" and "1".
------------------------------
------------------------------
Heaters
------------------------------
Winter is coming! Your first job during the contest is to design a
standard heater with fixed warm radius to warm all the houses.
Note:
Numbers of houses and heaters you are given are non-negative and
will not exceed 25000.
Positions of houses and heaters you are given are non-negative and
will not exceed 10^9.
As long as a house is in the heaters' warm radius range, it can be
warmed.
All the heaters follow your radius standard and the warm radius will
the same.
Example 1:
Input: [1,2,3],[2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we
use the radius 1 standard, then all the houses can be warmed.
Example 2:
Input: [1,2,3,4],[1,4]
Output: 1
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.
------------------------------
------------------------------
Number Complement
------------------------------
Given a positive integer, output its complement number. The
complement strategy is to flip the bits of its binary
representation.
Note:
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero
bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero
bits), and its complement is 0. So you need to output 0.
------------------------------
------------------------------
Total Hamming Distance
------------------------------
The Hamming distance between two integers is the number of positions
at which the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs
of the given numbers.
Example:
Input: 4, 14, 2
Output: 6
------------------------------
------------------------------
Sliding Window Median
------------------------------
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
mean of the two middle value.
Examples:
[2,3,4] , the median is 3
[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.
Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for
non-empty array.
------------------------------
------------------------------
Magical String
------------------------------
A magical string S consists of only '1' and '2' and obeys the
following rules:
The string S is magical because concatenating the number of
contiguous occurrences of characters '1' and '2' generates the
string S itself.
1 22 11 2 1 22 1 22 11 2 11 22 ......
1 2 2 1 1 2 1 2 2 1 2 2 ......
You can see that the occurrence sequence above is the S itself.
Note:
N will not exceed 100,000.
Example 1:
Input: 6
Output: 3
Explanation: The first 6 elements of magical string S is "12211" and
it contains three 1's, so return 3.
------------------------------
------------------------------
License Key Formatting
------------------------------
Now you are given a string S, which represents a software license
key which we would like to format. The string S is composed of
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
in the given string are possibly misplaced.
Example 1:
Input: S = "2-4A0r7-4k", K = 4
Output: "24A0-R74K"
Explanation: The string S has been split into two parts, each part
has 4 characters.
Example 2:
Input: S = "2-4A0r7-4k", K = 3
Output: "24-A0R-74K"
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.
Note:
------------------------------
------------------------------
Smallest Good Base
------------------------------
For an integer n, we call k>=2 a good base of n, if all digits of n
base k are 1.
Now given a string representing n, you should return the smallest
good base of n in string format.
Example 1:
Input: "13"
Output: "3"
Explanation: 13 base 3 is 111.
Example 2:
Input: "4681"
Output: "8"
Explanation: 4681 base 8 is 11111.
Example 3:
Input: "1000000000000000000"
Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.
Note:
------------------------------
------------------------------
------------------------------
Max Consecutive Ones
------------------------------
Given a binary array, find the maximum number of consecutive 1s in
this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are
consecutive 1s.
The maximum number of consecutive 1s is 3.
Note:
------------------------------
------------------------------
Predict the Winner
------------------------------
Given an array of scores that are non-negative integers. Player 1
picks one of the numbers from either end of the array followed by
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
continues until all the scores have been chosen. The player with the
maximum score wins.
Example 1:
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2. If he
chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If
player 2 chooses 5, then player 1 will be left with 1 (or 2). So,
final score of player 1 is 1 + 2 = 3, and player 2 is 5. Hence,
player 1 will never be the winner and you need to return False.
Example 2:
Note:
------------------------------
------------------------------
------------------------------
Zuma Game
------------------------------
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
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,
remove these balls. Keep doing this until no more balls can be
removed.
Find the minimal balls you have to insert to remove all the balls on
the table. If you cannot remove all the balls, output -1.
Examples:
Input: "WRRBBW", "RB"
Output: -1
Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW
Input:"G", "GGGGG"
Output: 2
Explanation: G -> G[G] -> GG[G] -> empty
Note:
You may assume that the initial row of balls on the table won’t have
any 3 or more consecutive balls with the same color.
The number of balls on the table won't exceed 20, and the string
represents these balls is called "board" in the input.
The number of balls in your hand won't exceed 5, and the string
represents these balls is called "hand" in the input.
Both input strings will be non-empty and only contain characters
'R','Y','B','G','W'.
------------------------------
------------------------------
------------------------------
Increasing Subsequences
------------------------------
Example:
Input: [4, 6, 7, 7]
Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7],
[7,7], [4,7,7]]
Note:
------------------------------
------------------------------
Construct the Rectangle
------------------------------
You need to output the length L and the width W of the web page you
designed in sequence.
Example:
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to
construct it are [1,4], [2,2], [4,1].
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.
Note:
The given area won't exceed 10,000,000 and is a positive integer
The web page's width and length you designed must be positive
integers.
------------------------------
------------------------------
Reverse Pairs
------------------------------
Given an array nums, we call (i, j) an important reverse pair if i
< j and nums[i] > 2*nums[j].
Example1:
Input: [1,3,2,3,1]
Output: 2
Example2:
Input: [2,4,3,5,1]
Output: 3
Note:
------------------------------
------------------------------
Target Sum
------------------------------
You are given a list of non-negative integers, a1, a2, ..., an, and
a target, S. Now you have 2 symbols + and -. For each integer, you
should choose one from + and - as its new symbol.
Find out how many ways to assign symbols to make sum of integers
equal to target S.
Example 1:
There are 5 ways to assign symbols to make the sum of nums be target
3.
Note:
The length of the given array is positive and will not exceed 20.
The sum of elements in the given array will not exceed 1000.
Your output answer is guaranteed to be fitted in a 32-bit integer.
------------------------------
------------------------------
Teemo Attacking
------------------------------
In LLP world, there is a hero called Teemo and his attacking can
make his enemy Ashe be in poisoned condition. Now, given the Teemo's
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.
Example 1:
Input: [1,4], 2
Output: 4
Explanation: At time point 1, Teemo starts attacking Ashe and makes
Ashe be poisoned immediately. This poisoned status will last 2
seconds until the end of time point 2. And at time point 4, Teemo
attacks Ashe again, and causes Ashe to be in poisoned status for
another 2 seconds. So you finally need to output 4.
Example 2:
Input: [1,2], 2
Output: 3
Explanation: At time point 1, Teemo starts attacking Ashe and makes
Ashe be poisoned. This poisoned status will last 2 seconds until the
end of time point 2. However, at the beginning of time point 2,
Teemo attacks Ashe again who is already in poisoned status. Since
the poisoned status won't add up together, though the second
poisoning attack will still work at time point 2, it will stop at
the end of time point 3. So you finally need to output 3.
Note:
You may assume the length of given time series array won't exceed
10000.
You may assume the numbers in the Teemo's attacking time series and
his poisoning time duration per attacking are non-negative integers,
which won't exceed 10,000,000.
------------------------------
------------------------------
Next Greater Element I
------------------------------
You are given two arrays (without duplicates) nums1 and nums2 where
nums1’s elements are subset of nums2. Find all the next greater
numbers for nums1's elements in the corresponding places of nums2.
Example 1:
Example 2:
Note:
------------------------------
------------------------------
Diagonal Traverse
------------------------------
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,4,7,5,3,6,8,9]
Explanation:
Note:
The total number of elements of the given matrix will not exceed
10,000.
------------------------------
------------------------------
------------------------------
Keyboard Row
------------------------------
Given a List of words, return the words that can be typed using
letters of alphabet on only one row's of American keyboard like the
image below.
Example 1:
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of
alphabet.
------------------------------
------------------------------
Find Mode in Binary Search Tree
------------------------------
Given a binary search tree (BST) with duplicates, find all the
mode(s) (the most frequently occurred element) in the given BST.
The left subtree of a node contains only nodes with keys less than
or equal to the node's key.
The right subtree of a node contains only nodes with keys greater
than or equal to the node's key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
Note:
If a tree has more than one mode, you can return them in any order.
Follow up:
Could you do that without using any extra space? (Assume that the
implicit stack space incurred due to recursion does not count).
------------------------------
------------------------------
IPO
------------------------------
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
on some projects to increase its capital before the IPO. Since it
has limited resources, it can only finish at most k distinct
projects before the IPO. Help LeetCode design the best way to
maximize its total capital after finishing at most k distinct
projects.
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
corresponding project. Initially, you have W capital. When you
finish a project, you will obtain its pure profit and the profit
will be added to your total capital.
Example 1:
Output: 4
Explanation: Since your initial capital is 0, you can only start the
project indexed 0.
After finishing it you will obtain profit 1 and your
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
finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is
0 + 1 + 3 = 4.
Note:
You may assume all numbers in the input are non-negative integers.
The length of Profits array and Capital array will not exceed
50,000.
The answer is guaranteed to fit in a 32-bit signed integer.
------------------------------
------------------------------
Next Greater Element II
------------------------------
Given a circular array (the next element of the last element is the
first element of the array), print the Next Greater Number for every
element. The Next Greater Number of a number x is the first greater
number to its traversing-order next in the array, which means you
could search circularly to find its next greater number. If it
doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; The number 2
can't find next greater number; The second 1's next greater number
needs to search circularly, which is also 2.
Note:
The length of given array won't exceed 10000.
------------------------------
------------------------------
Base 7
------------------------------
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note:
The input will be in range of [-1e7, 1e7].
------------------------------
------------------------------
------------------------------
Relative Ranks
------------------------------
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".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three athletes got the top three highest
scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
For the left two athletes, you just need to output their relative
ranks according to their scores.
Note:
------------------------------
------------------------------
Perfect Number
------------------------------
We define the Perfect Number is a positive integer that is equal to
the sum of all its positive divisors except itself.
Example:
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14
Note:
The input number n will not exceed 100,000,000. (1e8)
------------------------------
------------------------------
Most Frequent Subtree Sum
------------------------------
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
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.
Examples 1
Input:
5
/ \
2 -3
return [2, -3, 4], since all the values happen only once, return all
of them in any order.
Examples 2
Input:
5
/ \
2 -5
Note:
You may assume the sum of values in any subtree is in the range of
32-bit signed integer.
------------------------------
------------------------------
Find Bottom Left Tree Value
------------------------------
Given a binary tree, find the leftmost value in the last row of the
tree.
Example 1:
Input:
2
/ \
1 3
Output:
1
Example 2:
Input:
1
/ \
2 3
/ / \
4 5 6
/
7
Output:
7
Note:
You may assume the tree (i.e., the given root node) is not NULL.
------------------------------
------------------------------
Freedom Trail
------------------------------
Given a string ring, which represents the code engraved on the outer
ring and another string key, which represents the keyword needs to
be spelled. You need to find the minimum number of steps in order to
spell all the characters in the keyword.
At the stage of rotating the ring to spell the key character key[i]:
You can rotate the ring clockwise or anticlockwise one place, which
counts as 1 step. The final purpose of the rotation is to align one
of the string ring's characters at the 12:00 direction, where this
character must equal to the character key[i].
If the character key[i] has been aligned at the 12:00 direction, you
need to press the center button to spell, which also counts as 1
step. After the pressing, you could begin to spell the next
character in the key (next stage), otherwise, you've finished all
the spelling.
Example:
Note:
------------------------------
------------------------------
Find Largest Value in Each Tree Row
------------------------------
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
------------------------------
------------------------------
Longest Palindromic Subsequence
------------------------------
Example 1:
Input:
"bbbab"
Output:
Example 2:
Input:
"cbbd"
Output:
------------------------------
------------------------------
Super Washing Machines
------------------------------
You have n super washing machines on a line. Initially, each washing
machine has some dresses or is empty.
Example1
Input: [1,0,5]
Output: 3
Explanation:
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
Example2
Input: [0,3,0]
Output: 2
Explanation:
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
Example3
Input: [0,2,0]
Output: -1
Explanation:
It's impossible to make all the three washing machines have the same
number of dresses.
Note:
------------------------------
------------------------------
Detect Capital
------------------------------
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Note:
The input will be a non-empty word consisting of uppercase and
lowercase latin letters.
------------------------------
------------------------------
------------------------------
Longest Uncommon Subsequence II
------------------------------
The input will be a list of strings, and the output needs to be the
length of the longest uncommon subsequence. If the longest uncommon
subsequence doesn't exist, return -1.
Example 1:
Note:
All the given strings' lengths will not exceed 10.
The length of the given list will be in the range of [2, 50].
------------------------------
------------------------------
Continuous Subarray Sum
------------------------------
Example 1:
Example 2:
Note:
------------------------------
------------------------------
Longest Word in Dictionary through Deleting
------------------------------
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
Example 2:
Input:
s = "abpcplea", d = ["a","b","c"]
Output:
"a"
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won't exceed 1,000.
The length of all the strings in the input won't exceed 1,000.
------------------------------
------------------------------
Contiguous Array
------------------------------
Given a binary array, find the maximum length of a contiguous
subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal
number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray
with equal number of 0 and 1.
Note:
The length of the given binary array will not exceed 50,000.
------------------------------
------------------------------
Beautiful Arrangement
------------------------------
Example 1:
Input: 2
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).
Number at the 2nd position (i=2) is 2, and 2 is divisible by i
(i=2).
The second beautiful arrangement is [2, 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
1.
Note:
------------------------------
------------------------------
------------------------------
Minesweeper
------------------------------
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'
to '8') represents how many mines are adjacent to this revealed
square, and finally 'X' represents a revealed mine.
Now given the next click position (row and column indices) among all
the unrevealed squares ('M' or 'E'), return the board after
revealing this position according to the following rules:
Example 1:
Input:
Click : [3,0]
Output:
Explanation:
Example 2:
Input:
Output:
Explanation:
Note:
------------------------------
------------------------------
Minimum Absolute Difference in BST
------------------------------
Given a binary search tree with non-negative values, find the
minimum absolute difference between values of any two nodes.
Example:
Input:
1
\
3
/
2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference
between 2 and 1 (or between 2 and 3).
Note:
There are at least two nodes in this BST.
------------------------------
------------------------------
------------------------------
K-diff Pairs in an Array
------------------------------
Example 1:
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2,
3), (3, 4) and (4, 5).
Example 3:
Note:
Design the encode and decode methods for the TinyURL service. There
is no restriction on how your encode/decode algorithm should work.
You just need to ensure that a URL can be encoded to a tiny URL and
the tiny URL can be decoded to the original URL.
------------------------------
------------------------------
------------------------------
Complex Number Multiplication
------------------------------
Example 1:
Example 2:
Note:
------------------------------
------------------------------
Convert BST to Greater Tree
------------------------------
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
plus sum of all keys greater than the original key in BST.
Example:
------------------------------
------------------------------
Minimum Time Difference
------------------------------
Given a list of 24-hour clock time points in "Hour:Minutes" format,
find the minimum minutes difference between any two time points in
the list.
Example 1:
Input: ["23:59","00:00"]
Output: 1
Note:
The number of time points in the given list is at least 2 and won't
exceed 20000.
The input time is legal and ranges from 00:00 to 23:59.
------------------------------
------------------------------
Reverse String II
------------------------------
Example:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Restrictions:
------------------------------
------------------------------
01 Matrix
------------------------------
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and
right.
------------------------------
------------------------------
Diameter of Binary Tree
------------------------------
Given a binary tree, you need to compute the length of the diameter
of the tree. The diameter of a binary tree is the length of the
longest path between any two nodes in a tree. This path may or may
not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Note:
The length of path between two nodes is represented by the number of
edges between them.
------------------------------
------------------------------
------------------------------
------------------------------
Remove Boxes
------------------------------
Given several boxes with different colors represented by different
positive numbers.
You may experience several rounds to remove boxes until there is no
box left. Each time you can choose some continuous boxes with the
same color (composed of k boxes, k >= 1), remove them and get k*k
points.
Find the maximum points you can get.
Example 1:
Input:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
Output:
23
Explanation:
[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)
----> [1, 1] (3*3=9 points)
----> [] (2*2=4 points)
Note:
The number of boxes n would not exceed 100.
------------------------------
------------------------------
Friend Circles
------------------------------
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are
in a friend circle. The 2nd student himself is in a friend circle.
So return 2.
Example 2:
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and
2nd students are direct friends, so the 0th and 2nd students are
indirect friends. All of them are in the same friend circle, so
return 1.
Note:
N is in range [1,200].
M[i][i] = 1 for all students.
If M[i][j] = 1, then M[j][i] = 1.
------------------------------
------------------------------
------------------------------
Design TinyURL
------------------------------
Note: For the coding companion problem, please see: Encode and
Decode TinyURL.
Background:
TinyURL is a URL shortening service where you enter a URL such as
https://leetcode.com/problems/design-tinyurl and it returns a short
URL such as http://tinyurl.com/4e9iAk.
Requirements:
Each shortened URL must be unique; that is, no two different URLs
can be shortened to the same URL.
Note about Questions:Below are just a small subset of questions to
get you started. In real world, there could be many follow ups and
questions possible and the discussion is open-ended (No one true or
correct way to solve a problem). If you have more ideas or
questions, please ask in Discuss and we may compile it here!
Questions:
How many unique identifiers possible? Will you run out of unique
URLs?
Should the identifier be increment or not? Which is easier to
design? Pros and cons?
Mapping an identifier to an URL and its reversal - Does this problem
ring a bell to you?
How do you store the URLs? Does a simple flat file database work?
What is the bottleneck of the system? Is it read-heavy or write-
heavy?
Estimate the maximum number of URLs a single machine can store.
Estimate the maximum number of queries per second (QPS) for decoding
a shortened URL in a single machine.
How would you scale the service? For example, a viral link which is
shared in social media could result in a peak QPS at a moment's
notice.
How could you handle redundancy? i,e, if a server is down, how could
you ensure the service is still operational?
Keep URLs forever or prune, pros/cons? How we do pruning?
(Contributed by @alex_svetkin)
What API would you provide to a third-party developer? (Contributed
by @alex_svetkin)
If you can enable caching, what would you cache and what's the
expiry time? (Contributed by @Humandroid)
.hilight {
color: #d14;
background-color: #f7f7f9;
padding: 1px 3px;
border: 1px solid #e1e1e8"
}
------------------------------
------------------------------
License Key Formatting
------------------------------
Now you are given a string S, which represents a software license
key which we would like to format. The string S is composed of
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
in the given string are possibly misplaced.
Example 1:
Input: S = "2-4A0r7-4k", K = 4
Output: "24A0-R74K"
Explanation: The string S has been split into two parts, each part
has 4 characters.
Example 2:
Input: S = "2-4A0r7-4k", K = 3
Output: "24-A0R-74K"
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.
Note:
------------------------------
------------------------------
Longest Absolute File Path
------------------------------
Suppose we abstract our file system by a string in the following
manner:
dir
subdir1
subdir2
file.ext
The string
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsu
bdir2\n\t\t\tfile2.ext" represents:
dir
subdir1
file1.ext
subsubdir1
subdir2
subsubdir2
file2.ext
Note:
Design the encode and decode methods for the TinyURL service. There
is no restriction on how your encode/decode algorithm should work.
You just need to ensure that a URL can be encoded to a tiny URL and
the tiny URL can be decoded to the original URL.
------------------------------
------------------------------
Coin Change 2
------------------------------
Note:
You can assume that
Example 1:
Example 2:
Example 3:
------------------------------
------------------------------
Poor Pigs
------------------------------
There are 1000 buckets, one and only one of them contains poison,
the rest are filled with water. They all look the same. If a pig
drinks that poison it will die within 15 minutes. What is the
minimum amount of pigs you need to figure out which bucket contains
the poison within one hour.
Follow-up:
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"
bucket within p minutes? There is exact one bucket with poison.
------------------------------
------------------------------
Minimum Genetic Mutation
------------------------------
A gene string can be represented by an 8-character long string, with
choices from "A", "C", "G", "T".
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.
Note:
start: "AACCGGTT"
end: "AACCGGTA"
bank: ["AACCGGTA"]
return: 1
Example 2:
start: "AACCGGTT"
end: "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
return: 2
Example 3:
start: "AAAAACCC"
end: "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
return: 3
------------------------------
------------------------------
LFU Cache
------------------------------
Design and implement a data structure for Least Frequently Used
(LFU) cache. It should support the following operations: get and
put.
get(key) - Get the value (will always be positive) of the key if the
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
that have the same frequency), the least recently used key would be
evicted.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LFUCache cache = new LFUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.get(3); // returns 3.
cache.put(4, 4); // evicts key 1.
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
------------------------------
------------------------------
------------------------------
Longest Palindromic Subsequence
------------------------------
Example 1:
Input:
"bbbab"
Output:
Example 2:
Input:
"cbbd"
Output: