0% found this document useful (0 votes)
37 views

Staple - 1

There are three ways to summarize this document: 1. The document provides examples and explanations for how to solve four Leetcode problems: Single Element in a Sorted Array, Coin Change 2, Two Sum, and Longest Substring Without Repeating Characters. It describes the problems, provides sample inputs and outputs, and notes complexity requirements for solutions. 2. This document contains descriptions, examples, and notes for solving four algorithm problems: finding a single unique element in a sorted array, computing coin combinations to make a total amount, finding index pairs of numbers that sum to a target, and determining the longest substring without repeating characters. Complexity constraints are provided for each problem. 3. Leetcode

Uploaded by

tomandjerry625
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Staple - 1

There are three ways to summarize this document: 1. The document provides examples and explanations for how to solve four Leetcode problems: Single Element in a Sorted Array, Coin Change 2, Two Sum, and Longest Substring Without Repeating Characters. It describes the problems, provides sample inputs and outputs, and notes complexity requirements for solutions. 2. This document contains descriptions, examples, and notes for solving four algorithm problems: finding a single unique element in a sorted array, computing coin combinations to make a total amount, finding index pairs of numbers that sum to a target, and determining the longest substring without repeating characters. Complexity constraints are provided for each problem. 3. Leetcode

Uploaded by

tomandjerry625
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Output: 4

Leetcode Offline Explanation: there are four ways to make up the amount:
5=5
------------------------------ 5=2+2+1
Single Element in a Sorted Array 5=2+1+1+1
------------------------------ 5=1+1+1+1+1

Given a sorted array consisting of only integers where every element


appears twice except for one element which appears once. Find this Example 2:
single element that appears only once.
Input: amount = 3, coins = [2]
Output: 0
Example 1: Explanation: the amount of 3 cannot be made up just with coins of 2.

Input: [1,1,2,3,3,4,4,8,8]
Output: 2 Example 3:

Input: amount = 10, coins = [10]


Output: 1
Example 2:

Input: [3,3,7,7,10,11,11] ------------------------------


Output: 10 ------------------------------
Largest Palindrome Product
------------------------------
Find the largest palindrome made from the product of two n-digit
Note: numbers.
Your solution should run in O(log n) time and O(1) space. Since the result could be very large, you should return the largest
palindrome mod 1337.

------------------------------ Example:
------------------------------ Input: 2
Coin Change 2 Output: 987
------------------------------ Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

You are given coins of different denominations and a total amount of


money. Write a function to compute the number of combinations that
make up that amount. You may assume that you have infinite number of
each kind of coin. Note:
The range of n is [1,8].

Note: ------------------------------
You can assume that ------------------------------
Find All Duplicates in an Array
0 <= amount <= 5000 ------------------------------
1 <= coin <= 5000 Given an array of integers, 1 &le; a[i] &le; n (n = size of array),
the number of coins is less than 500 some elements appear twice and others appear once.
the answer is guaranteed to fit into signed 32-bit integer
Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?


Example 1:
Example:
Input: amount = 5, coins = [1, 2, 5]

Input: the answer must be a substring, "pwke" is a subsequence and not a


[4,3,2,7,8,2,3,1] substring.
------------------------------
Output: ------------------------------
[2,3] Median of Two Sorted Arrays
------------------------------
------------------------------ There are two sorted arrays nums1 and nums2 of size m and n
------------------------------ respectively.
Two Sum
------------------------------ Find the median of the two sorted arrays. The overall run time
Given an array of integers, return indices of the two numbers such complexity should be O(log (m+n)).
that they add up to a specific target.
Example 1:
You may assume that each input would have exactly one solution, and
you may not use the same element twice. nums1 = [1, 3]
nums2 = [2]

Example: The median is 2.0

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, Example 2:


return [0, 1].
nums1 = [1, 2]
nums2 = [3, 4]
------------------------------
------------------------------ The median is (2 + 3)/2 = 2.5
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 Longest Palindromic Substring
return it as a linked list. ------------------------------
Given a string s, find the longest palindromic substring in s. You
You may assume the two numbers do not contain any leading zero, may assume that the maximum length of s is 1000.
except the number 0 itself.
Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Input: "babad"


Output: 7 -> 0 -> 8
------------------------------ Output: "bab"
------------------------------
Longest Substring Without Repeating Characters Note: "aba" is also a valid answer.
------------------------------
Given a string, find the length of the longest substring without
repeating characters.
Example:
Examples:
Input: "cbbd"
Given "abcabcbb", the answer is "abc", which the length is 3.
Output: "bb"
Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that ------------------------------
------------------------------
ZigZag Conversion Note:
------------------------------ The input is assumed to be a 32-bit signed integer. Your function
should return 0 when the reversed integer overflows.
The string "PAYPALISHIRING" is written in a zigzag pattern on a
given number of rows like this: (you may want to display this ------------------------------
pattern in a fixed font for better legibility) ------------------------------
String to Integer (atoi)
P A H N ------------------------------
A P L S I I G Implement atoi to convert a string to an integer.
Y I R
Hint: Carefully consider all possible input cases. If you want a
challenge, please do not see below and ask yourself what are the
And then read line by line: "PAHNAPLSIIGYIR" possible input cases.

Write the code that will take a string and make this conversion Notes:
given a number of rows: It is intended for this problem to be specified vaguely (ie, no
given input specs). You are responsible to gather all the input
string convert(string text, int nRows); requirements up front.

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".


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
Reverse Integer click the reload button to reset your code definition.
------------------------------
Reverse digits of an integer.
spoilers alert... click to show requirements for atoi.

Example1: x = 123, return 321 Requirements for atoi:


Example2: x = -123, return -321
The function first discards as many whitespace characters as
necessary until the first non-whitespace character is found. Then,
click to show spoilers. starting from this character, takes an optional initial plus or
minus sign followed by as many numerical digits as possible, and
Have you thought about this? interprets them as a numerical value.

Here are some good questions to ask before coding. Bonus points for The string can contain additional characters after those that form
you if you have already thought through this! the integral number, which are ignored and have no effect on the
behavior of this function.
If the integer's last digit is 0, what should the output be? ie,
cases such as 10, 100. If the first sequence of non-whitespace characters in str is not a
valid integral number, or if no such sequence exists because either
Did you notice that the reversed integer might overflow? Assume the str is empty or it contains only whitespace characters, no
input is a 32-bit integer, then the reverse of 1000000003 overflows. conversion is performed.
How should you handle such cases?
If no valid conversion could be performed, a zero value is returned.
For the purpose of this problem, assume that your function returns 0 If the correct value is out of the range of representable values,
when the reversed integer overflows. INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

------------------------------
------------------------------

Palindrome Number
------------------------------ Note: You may not slant the container and n is at least 2.
Determine whether an integer is a palindrome. Do this without extra
space. ------------------------------
------------------------------
click to show spoilers. Integer to Roman
------------------------------
Some hints: Given an integer, convert it to a roman numeral.

Could negative integers be palindromes? (ie, -1)


Input is guaranteed to be within the range from 1 to 3999.
If you are thinking of converting the integer to string, note the ------------------------------
restriction of using extra space. ------------------------------
Roman to Integer
You could also try reversing an integer. However, if you have solved ------------------------------
the problem "Reverse Integer", you know that the reversed integer Given a roman numeral, convert it to an integer.
might overflow. How would you handle such case?
Input is guaranteed to be within the range from 1 to 3999.
There is a more generic way of solving this problem. ------------------------------
------------------------------
Longest Common Prefix
------------------------------ ------------------------------
------------------------------ Write a function to find the longest common prefix string amongst an
Regular Expression Matching array of strings.
------------------------------
Implement regular expression matching with support for '.' and '*'. ------------------------------
------------------------------
3Sum
'.' Matches any single character. ------------------------------
'*' Matches zero or more of the preceding element. 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
The matching should cover the entire input string (not partial). gives the sum of zero.

The function prototype should be: Note: The solution set must not contain duplicate triplets.
bool isMatch(const char *s, const char *p)

Some examples: For example, given array S = [-1, 0, 1, 2, -1, -4],


isMatch("aa","a") → false
isMatch("aa","aa") → true A solution set is:
isMatch("aaa","aa") → false [
isMatch("aa", "a*") → true [-1, 0, 1],
isMatch("aa", ".*") → true [-1, -1, 2]
isMatch("ab", ".*") → true ]
isMatch("aab", "c*a*b") → true
------------------------------
------------------------------ ------------------------------
------------------------------ 3Sum Closest
Container With Most Water ------------------------------
------------------------------ Given an array S of n integers, find three integers in S such that
Given n non-negative integers a1, a2, ..., an, where each represents the sum is closest to a given number, target. Return the sum of the
a point at coordinate (i, ai). n vertical lines are drawn such that three integers. You may assume that each input would have exactly
the two endpoints of line i is at (i, ai) and (i, 0). Find two one solution.
lines, which together with x-axis forms a container, such that the
container contains the most water.
For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). For example,

------------------------------
------------------------------ Given linked list: 1->2->3->4->5, and n = 2.
Letter Combinations of a Phone Number
------------------------------ After removing the second node from the end, the linked list
Given a digit string, return all possible letter combinations that becomes 1->2->3->5.
the number could represent.

Note:
A mapping of digit to letters (just like on the telephone buttons) Given n will always be valid.
is given below. Try to do this in one pass.

------------------------------
------------------------------
Input:Digit string "23" Valid Parentheses
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. ------------------------------
Given a string containing just the characters '(', ')', '{', '}',
'[' and ']', determine if the input string is valid.

Note: The brackets must close in the correct order, "()" and "()[]{}" are
Although the above answer is in lexicographical order, your answer all valid but "(]" and "([)]" are not.
could be in any order you want.
------------------------------
------------------------------ ------------------------------
------------------------------ Merge Two Sorted Lists
4Sum ------------------------------
------------------------------ Merge two sorted linked lists and return it as a new list. The new
Given an array S of n integers, are there elements a, b, c, and d in list should be made by splicing together the nodes of the first two
S such that a + b + c + d = target? Find all unique quadruplets in lists.
the array which gives the sum of target. ------------------------------
------------------------------
Note: The solution set must not contain duplicate quadruplets. Generate Parentheses
------------------------------

Given n pairs of parentheses, write a function to generate all


For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. combinations of well-formed parentheses.

A solution set is:


[
[-1, 0, 0, 1], For example, given n = 3, a solution set is:
[-2, -1, 1, 2],
[-2, 0, 0, 2]
] [
"((()))",
------------------------------ "(()())",
------------------------------ "(())()",
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 k = 3, you should return: 3->2->1->4->5
Merge k Sorted Lists
------------------------------ ------------------------------
------------------------------
Merge k sorted linked lists and return it as one sorted list. Remove Duplicates from Sorted Array
Analyze and describe its complexity. ------------------------------

------------------------------ Given a sorted array, remove the duplicates in place such that each
------------------------------ element appear only once and return the new length.
Swap Nodes in Pairs
------------------------------
Do not allocate extra space for another array, you must do this in
Given a linked list, swap every two adjacent nodes and return its place with constant memory.
head.

For example,
For example, Given input array nums = [1,1,2],
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your function should return length = 2, with the first two elements
of nums being 1 and 2 respectively. It doesn't matter what you leave
Your algorithm should use only constant space. You may not modify beyond the new length.
the values in the list, only nodes itself can be changed.
------------------------------
------------------------------ ------------------------------
------------------------------ Remove Element
Reverse Nodes in k-Group ------------------------------
------------------------------ Given an array and a value, remove all instances of that value in
place and return the new length.
Given a linked list, reverse the nodes of a linked list k at a time
and return its modified list.
Do not allocate extra space for another array, you must do this in
place with constant memory.

k is a positive integer and is less than or equal to the length of The order of elements can be changed. It doesn't matter what you
the linked list. If the number of nodes is not a multiple of k then leave beyond the new length.
left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be Example:
changed. Given input array nums = [3,2,2,3], val = 3

Only constant memory is allowed.


Your function should return length = 2, with the first two elements
of nums being 2.
For example,
Given this linked list: 1->2->3->4->5
Try two pointers.
Did you use the property of "the order of elements can be
changed"?
For k = 2, you should return: 2->1->4->3->5 What happens when the elements to remove are rare?

------------------------------
------------------------------
Implement strStr() The replacement must be in-place, do not allocate extra memory.
------------------------------

Implement strStr(). Here are some examples. Inputs are in the left-hand column and its
corresponding outputs are in the right-hand column.
1,2,3 &#8594; 1,3,2
Returns the index of the first occurrence of needle in haystack, or 3,2,1 &#8594; 1,2,3
-1 if needle is not part of haystack. 1,1,5 &#8594; 1,5,1

------------------------------ ------------------------------
------------------------------ ------------------------------
Divide Two Integers Longest Valid Parentheses
------------------------------ ------------------------------
Given a string containing just the characters '(' and ')', find the
Divide two integers without using multiplication, division and mod length of the longest valid (well-formed) parentheses substring.
operator.

For "(()", the longest valid parentheses substring is "()", which


If it is overflow, return MAX_INT. has length = 2.

------------------------------
------------------------------ Another example is ")()())", where the longest valid parentheses
Substring with Concatenation of All Words substring is "()()", which has length = 4.
------------------------------
------------------------------
You are given a string, s, and a list of words, words, that are all ------------------------------
of the same length. Find all starting indices of substring(s) in s Search in Rotated Sorted Array
that is a concatenation of each word in words exactly once and ------------------------------
without any intervening characters. Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).


For example, given:
s: "barfoothefoobarman" You are given a target value to search. If found in the array return
words: ["foo", "bar"] its index, otherwise return -1.

You may assume no duplicate exists in the array.


------------------------------
You should return the indices: [0,9]. ------------------------------
(order does not matter). Search for a Range
------------------------------
------------------------------ Given an array of integers sorted in ascending order, find the
------------------------------ starting and ending position of a given target value.
Next Permutation
------------------------------ Your algorithm's runtime complexity must be in the order of O(log
n).
Implement next permutation, which rearranges numbers into the
lexicographically next greater permutation of numbers. If the target is not found in the array, return [-1, -1].

If such arrangement is not possible, it must rearrange it as the For example,


lowest possible order (ie, sorted in ascending order). Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

...and its solution numbers marked in red.


------------------------------
------------------------------ ------------------------------
Search Insert Position ------------------------------
------------------------------ Count and Say
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 The count-and-say sequence is the sequence of integers beginning as
were inserted in order. follows:
1, 11, 21, 1211, 111221, ...
You may assume no duplicates in the array.

Here are few examples. 1 is read off as "one 1" or 11.


[1,3,5,6], 5 &#8594; 2 11 is read off as "two 1s" or 21.
[1,3,5,6], 2 &#8594; 1 21 is read off as "one 2, then one 1" or 1211.
[1,3,5,6], 7 &#8594; 4
[1,3,5,6], 0 &#8594; 0

------------------------------ Given an integer n, generate the nth sequence.


------------------------------
Valid Sudoku
------------------------------
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Note: The sequence of integers will be represented as a string.
Rules.

The Sudoku board could be partially filled, where empty cells are ------------------------------
filled with the character '.'. ------------------------------
Combination Sum
------------------------------

A partially filled sudoku which is valid. Given a set of candidate numbers (C) (without duplicates) and a
target number (T), find all unique combinations in C where the
candidate numbers sums to T.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable.
Only the filled cells need to be validated. The same repeated number may be chosen from C unlimited number of
times.
------------------------------
------------------------------
Sudoku Solver Note:
------------------------------
Write a program to solve a Sudoku puzzle by filling the empty cells. All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

For example, given candidate set [2, 3, 6, 7] and target 7,


A solution set is:
A sudoku puzzle...
[
[7],
[2, 2, 3]
]
Trapping Rain Water
------------------------------
------------------------------
------------------------------ Given n non-negative integers representing an elevation map where
Combination Sum II the width of each bar is 1, compute how much water it is able to
------------------------------ trap after raining.

Given a collection of candidate numbers (C) and a target number (T),


find all unique combinations in C where the candidate numbers sums
to T. For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

Each number in C may only be used once in the combination.

Note:
The above elevation map is represented by array
All numbers (including target) will be positive integers. [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue
The solution set must not contain duplicate combinations. section) are being trapped. Thanks Marcos for contributing this
image!
------------------------------
------------------------------
Multiply Strings
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target ------------------------------
8, Given two non-negative integers num1 and num2 represented as
A solution set is: strings, return the product of num1 and num2.

[ Note:
[1, 7],
[1, 2, 5], The length of both num1 and num2 is < 110.
[2, 6], Both num1 and num2 contains only digits 0-9.
[1, 1, 6] Both num1 and num2 does not contain any leading zero.
] You must not use any built-in BigInteger library or convert the
inputs to integer directly.

------------------------------
------------------------------ ------------------------------
First Missing Positive ------------------------------
------------------------------ Wildcard Matching
------------------------------
Given an unsorted integer array, find the first missing positive Implement wildcard pattern matching with support for '?' and '*'.
integer.

'?' Matches any single character.


'*' Matches any sequence of characters (including the empty
For example, sequence).
Given [1,2,0] return 3,
and [3,4,-1,1] return 2. The matching should cover the entire input string (not partial).

The function prototype should be:


bool isMatch(const char *s, const char *p)
Your algorithm should run in O(n) time and uses constant space.
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 ------------------------------
Permutations II
------------------------------ ------------------------------
------------------------------
Jump Game II Given a collection of numbers that might contain duplicates, return
------------------------------ all possible unique permutations.

Given an array of non-negative integers, you are initially


positioned at the first index of the array.
For example,
[1,1,2] have the following unique permutations:
Each element in the array represents your maximum jump length at
that position. [
[1,1,2],
[1,2,1],
Your goal is to reach the last index in the minimum number of jumps. [2,1,1]
]

For example: ------------------------------


Given array A = [2,3,1,1,4] ------------------------------
Rotate Image
------------------------------
The minimum number of jumps to reach the last index is 2. (Jump 1 You are given an n x n 2D matrix representing an image.
step from index 0 to 1, then 3 steps to the last index.) Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
------------------------------
Note: ------------------------------
You can assume that you can always reach the last index. Group Anagrams
------------------------------ ------------------------------
------------------------------ Given an array of strings, group anagrams together.
Permutations
------------------------------
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Given a collection of distinct numbers, return all possible Return:
permutations.
[
["ate", "eat","tea"],
["nat","tan"],
For example, ["bat"]
[1,2,3] have the following permutations: ]

[ Note: All inputs will be in lower-case.


[1,2,3], ------------------------------
[1,3,2], ------------------------------
[2,1,3], Pow(x, n)
[2,3,1], ------------------------------
[3,1,2], Implement pow(x, n).
[3,2,1]
------------------------------ click to show more practice.
------------------------------
N-Queens More practice:
------------------------------
The n-queens puzzle is the problem of placing n queens on an n×n If you have figured out the O(n) solution, try coding another
chessboard such that no two queens attack each other. solution using the divide and conquer approach, which is more
subtle.

------------------------------
Given an integer n, return all distinct solutions to the n-queens ------------------------------
puzzle. Spiral Matrix
------------------------------
Each solution contains a distinct board configuration of the n- Given a matrix of m x n elements (m rows, n columns), return all
queens' placement, where 'Q' and '.' both indicate a queen and an elements of the matrix in spiral order.
empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle: For example,
Given the following matrix:
[
[".Q..", // Solution 1
"...Q", [
"Q...", [ 1, 2, 3 ],
"..Q."], [ 4, 5, 6 ],
[ 7, 8, 9 ]
["..Q.", // Solution 2 ]
"Q...",
"...Q",
".Q.."] You should return [1,2,3,6,9,8,7,4,5].
]
------------------------------
------------------------------ ------------------------------
------------------------------ Jump Game
N-Queens II ------------------------------
------------------------------
Follow up for N-Queens problem. Given an array of non-negative integers, you are initially
positioned at the first index of the array.
Now, instead outputting board configurations, return the total
number of distinct solutions.
Each element in the array represents your maximum jump length at
that position.
------------------------------
------------------------------
Maximum Subarray Determine if you are able to reach the last index.
------------------------------

Find the contiguous subarray within an array (containing at least


one number) which has the largest sum. For example:
A = [2,3,1,1,4], return true.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],


the contiguous subarray [4,-1,2,1] has the largest sum = 6. A = [3,2,1,0,4], return false.

------------------------------

------------------------------ ------------------------------
Merge Intervals Spiral Matrix II
------------------------------ ------------------------------
Given a collection of intervals, merge all overlapping intervals. Given an integer n, generate a square matrix filled with elements
from 1 to n2 in spiral order.

For example,
Given [1,3],[2,6],[8,10],[15,18], For example,
return [1,6],[8,10],[15,18]. Given n = 3,

------------------------------ You should return the following matrix:


------------------------------
Insert Interval [
------------------------------ [ 1, 2, 3 ],
Given a set of non-overlapping intervals, insert a new interval into [ 8, 9, 4 ],
the intervals (merge if necessary). [ 7, 6, 5 ]
]
You may assume that the intervals were initially sorted according to
their start times. ------------------------------
------------------------------
Permutation Sequence
Example 1: ------------------------------
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5], The set [1,2,3,&#8230;,n] contains a total of n! unique
[6,9]. permutations.

By listing and labeling all of the permutations in order,


We get the following sequence (ie, for n = 3):
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as "123"
[1,2],[3,10],[12,16]. "132"
"213"
"231"
"312"
This is because the new interval [4,9] overlaps with [3,5],[6,7], "321"
[8,10].

------------------------------
------------------------------ Given n and k, return the kth permutation sequence.
Length of Last Word
------------------------------ Note: Given n will be between 1 and 9 inclusive.
Given a string s consists of upper/lower-case alphabets and empty ------------------------------
space characters ' ', return the length of last word in the string. ------------------------------
Rotate List
If the last word does not exist, return 0. ------------------------------
Given a list, rotate the list to the right by k places, where k is
Note: A word is defined as a character sequence consists of non- non-negative.
space characters only.
For example:
Given 1->2->3->4->5->NULL and k = 2,
For example, return 4->5->1->2->3->NULL.
Given s = "Hello World", ------------------------------
return 5. ------------------------------
Unique Paths
------------------------------ ------------------------------
A robot is located at the top-left corner of a m x n grid (marked
'Start' in the diagram below).
Some examples:
The robot can only move either down or right at any point in time. "0" => true
The robot is trying to reach the bottom-right corner of the grid " 0.1 " => true
(marked 'Finish' in the diagram below). "abc" => false
"1 a" => false
How many possible unique paths are there? "2e10" => true

Note: It is intended for the problem statement to be ambiguous. You


Above is a 3 x 7 grid. How many possible unique paths are there? should gather all requirements up front before implementing one.

Note: m and n will be at most 100.


------------------------------ Update (2015-02-10):
------------------------------ The signature of the C++ function had been updated. If you still see
Unique Paths II your function signature accepts a const char * argument, please
------------------------------ click the reload button to reset your code definition.
Follow up for "Unique Paths":
------------------------------
Now consider if some obstacles are added to the grids. How many ------------------------------
unique paths would there be? Plus One
------------------------------
An obstacle and empty space is marked as 1 and 0 respectively in the Given a non-negative integer represented as a non-empty array of
grid. digits, plus one to the integer.

For example, You may assume the integer do not contain any leading zero, except
There is one obstacle in the middle of a 3x3 grid as illustrated the number 0 itself.
below.
The digits are stored such that the most significant digit is at the
[ head of the list.
[0,0,0], ------------------------------
[0,1,0], ------------------------------
[0,0,0] Add Binary
] ------------------------------

The total number of unique paths is 2. Given two binary strings, return their sum (also a binary string).

Note: m and n will be at most 100.


------------------------------
------------------------------ For example,
Minimum Path Sum a = "11"
------------------------------ b = "1"
Given a m x n grid filled with non-negative numbers, find a path Return "100".
from top left to bottom right which minimizes the sum of all numbers
along its path. ------------------------------
------------------------------
Note: You can only move either down or right at any point in time. Text Justification
------------------------------ ------------------------------
------------------------------
Valid Number 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)
Validate if a given string is numeric. justified.

------------------------------
Sqrt(x)
------------------------------
You should pack your words in a greedy approach; that is, pack as Implement int sqrt(int x).
many words as you can in each line. Pad extra spaces ' ' when
necessary so that each line has exactly L characters. Compute and return the square root of x.
------------------------------
------------------------------
Climbing Stairs
Extra spaces between words should be distributed as evenly as ------------------------------
possible. If the number of spaces on a line do not divide evenly You are climbing a stair case. It takes n steps to reach to the top.
between words, the empty slots on the left will be assigned more
spaces than the slots on the right. Each time you can either climb 1 or 2 steps. In how many distinct
ways can you climb to the top?

For the last line of text, it should be left justified and no extra Note: Given n will be a positive integer.
space is inserted between words.
------------------------------
------------------------------
Simplify Path
For example, ------------------------------
words: ["This", "is", "an", "example", "of", "text", Given an absolute path for a file (Unix-style), simplify it.
"justification."]
L: 16. For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Return the formatted lines as:


click to show corner cases.
[
"This is an", Corner Cases:
"example of text",
"justification. "
]
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/'
together, such as "/home//foo/".
Note: Each word is guaranteed not to exceed L in length. In this case, you should ignore redundant slashes and return "/home/
foo".

click to show corner cases. ------------------------------


------------------------------
Corner Cases: Edit Distance
------------------------------

A line other than the last line might contain only one word. What Given two words word1 and word2, find the minimum number of steps
should you do in this case? required to convert word1 to word2. (each operation is counted as 1
In this case, that line should be left-justified. step.)

------------------------------
You have the following 3 operations permitted on a word: [23, 30, 34, 50]
]

a) Insert a character Given target = 3, return true.


b) Delete a character ------------------------------
c) Replace a character ------------------------------
Sort Colors
------------------------------ ------------------------------
------------------------------
Set Matrix Zeroes 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.
Given a m x n matrix, if an element is 0, set its entire row and
column to 0. Do it in place.

Here, we will use the integers 0, 1, and 2 to represent the color


click to show follow up. red, white, and blue respectively.

Follow up:

Note:
Did you use extra space? You are not suppose to use the library's sort function for this
A straight forward solution using O(mn) space is probably a bad problem.
idea.
A simple improvement uses O(m + n) space, but still not the best
solution. click to show follow up.
Could you devise a constant space solution?

Follow up:
------------------------------ A rather straight forward solution is a two-pass algorithm using
------------------------------ counting sort.
Search a 2D Matrix First, iterate the array counting number of 0's, 1's, and 2's, then
------------------------------ overwrite array with total number of 0's, then 1's and followed by
Write an efficient algorithm that searches for a value in an m x n 2's.
matrix. This matrix has the following properties: Could you come up with an one-pass algorithm using only constant
space?

Integers in each row are sorted from left to right. ------------------------------


The first integer of each row is greater than the last integer of ------------------------------
the previous row. Minimum Window Substring
------------------------------

Given a string S and a string T, find the minimum window in S which


will contain all the characters in T in complexity O(n).
For example,

Consider the following matrix:


For example,
S = "ADOBECODEBANC"
[ T = "ABC"
[1, 3, 5, 7],
[10, 11, 16, 20],

Minimum window is "BANC". [1,2,3],


[1,3],
[2,3],
[1,2],
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 Word Search
will always be only one unique minimum window in S. ------------------------------

------------------------------ Given a 2D board and a word, find if the word exists in the grid.
------------------------------
Combinations
------------------------------ The word can be constructed from letters of sequentially adjacent
cell, where "adjacent" cells are those horizontally or vertically
Given two integers n and k, return all possible combinations of k neighboring. The same letter cell may not be used more than once.
numbers out of 1 ... n.

For example, For example,


If n = 4 and k = 2, a solution is: Given board =

[
['A','B','C','E'],
[ ['S','F','C','S'],
[2,4], ['A','D','E','E']
[3,4], ]
[2,3],
[1,2],
[1,3], word = "ABCCED", -> returns true,
[1,4], word = "SEE", -> returns true,
] word = "ABCB", -> returns false.

------------------------------ ------------------------------
------------------------------ ------------------------------
Subsets Remove Duplicates from Sorted Array II
------------------------------ ------------------------------

Given a set of distinct integers, nums, return all possible subsets. Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
Note: The solution set must not contain duplicate subsets.

For example,
For example, Given sorted array nums = [1,1,1,2,2,3],
If nums = [1,2,3], a solution is:

Your function should return length = 5, with the first five elements
of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave
[ beyond the new length.
[3],
[1], ------------------------------
[2], ------------------------------
Search in Rotated Sorted Array II
------------------------------ Above is a histogram where width of each bar is 1, given height =
[2,1,5,6,2,3].
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?


The largest rectangle is shown in the shaded area, which has area =
10 unit.
Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). For example,


Given heights = [2,1,5,6,2,3],
Write a function to determine if a given target is in the array. return 10.

The array may contain duplicates. ------------------------------


------------------------------ ------------------------------
------------------------------ Maximal Rectangle
Remove Duplicates from Sorted List II ------------------------------
------------------------------
Given a 2D binary matrix filled with 0's and 1's, find the largest
Given a sorted linked list, delete all nodes that have duplicate rectangle containing only 1's and return its area.
numbers, leaving only distinct numbers from the original list.

For example, given the following matrix:


For example,
Given 1->2->3->3->4->4->5, return 1->2->5. 1 0 1 0 0
Given 1->1->1->2->3, return 2->3. 1 0 1 1 1
1 1 1 1 1
------------------------------ 1 0 0 1 0
------------------------------
Remove Duplicates from Sorted List Return 6.
------------------------------
------------------------------
Given a sorted linked list, delete all duplicates such that each ------------------------------
element appear only once. Partition List
------------------------------
Given a linked list and a value x, partition it such that all nodes
For example, less than x come before nodes greater than or equal to x.
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
You should preserve the original relative order of the nodes in each
------------------------------ of the two partitions.
------------------------------
Largest Rectangle in Histogram
------------------------------ For example,
Given 1->4->3->2->5->2 and x = 3,
Given n non-negative integers representing the histogram's bar return 1->2->2->4->3->5.
height where the width of each bar is 1, find the area of largest
rectangle in the histogram. ------------------------------
------------------------------
Scramble String
------------------------------

scrambled string of s1.


Given a string s1, we may represent it as a binary tree by
partitioning it to two non-empty substrings recursively. ------------------------------
------------------------------
Merge Sorted Array
Below is one possible representation of s1 = "great": ------------------------------
Given two sorted integer arrays nums1 and nums2, merge nums2 into
nums1 as one sorted array.
great
/ \
gr eat Note:
/ \ / \ You may assume that nums1 has enough space (size that is greater or
g r e at equal to m + n) to hold additional elements from nums2. The number
/ \ of elements initialized in nums1 and nums2 are m and n respectively.
a t ------------------------------
------------------------------
Gray Code
To scramble the string, we may choose any non-leaf node and swap its ------------------------------
two children. The gray code is a binary numeral system where two successive values
differ in only one bit.

For example, if we choose the node "gr" and swap its two children, Given a non-negative integer n representing the total number of bits
it produces a scrambled string "rgeat". in the code, print the sequence of gray code. A gray code sequence
must begin with 0.

rgeat For example, given n = 2, return [0,1,3,2]. Its gray code sequence
/ \ is:
rg eat
/ \ / \ 00 - 0
r g e at 01 - 1
/ \ 11 - 3
a t 10 - 2

We say that "rgeat" is a scrambled string of "great". Note:


For a given n, a gray code sequence is not uniquely defined.

Similarly, if we continue to swap the children of nodes "eat" and For example, [0,2,3,1] is also a valid gray code sequence according
"at", it produces a scrambled string "rgtae". to the above definition.

For now, the judge is able to judge based on one instance of gray
rgtae code sequence. Sorry about that.
/ \ ------------------------------
rg tae ------------------------------
/ \ / \ Subsets II
r g ta e ------------------------------
/ \
t a Given a collection of integers that might contain duplicates, nums,
return all possible subsets.

We say that "rgtae" is a scrambled string of "great". Note: The solution set must not contain duplicate subsets.

Given two strings s1 and s2 of the same length, determine if s2 is a For example,
If nums = [1,2,2], a solution is: Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.
[
[2],
[1], Note:
[1,2,2], Given m, n satisfy the following condition:
[2,2], 1 ≤ m ≤ n ≤ length of list.
[1,2],
[] ------------------------------
] ------------------------------
Restore IP Addresses
------------------------------ ------------------------------
------------------------------ Given a string containing only digits, restore it by returning all
Decode Ways possible valid IP address combinations.
------------------------------

A message containing letters from A-Z is being encoded to numbers For example:
using the following mapping: Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


'A' -> 1
'B' -> 2 ------------------------------
... ------------------------------
'Z' -> 26 Binary Tree Inorder Traversal
------------------------------
Given a binary tree, return the inorder traversal of its nodes'
values.
Given an encoded message containing digits, determine the total
number of ways to decode it.
For example:
Given binary tree [1,null,2,3],

For example, 1
Given encoded message "12", \
it could be decoded as "AB" (1 2) or "L" (12). 2
/
3

The number of ways decoding "12" is 2.

------------------------------ return [1,3,2].


------------------------------
Reverse Linked List II
------------------------------ Note: Recursive solution is trivial, could you do it iteratively?
------------------------------
Reverse a linked list from position m to n. Do it in-place and in ------------------------------
one-pass. Unique Binary Search Trees II
------------------------------
Given an integer n, generate all structurally unique BST's (binary
search trees) that store values 1...n.
For example:

------------------------------
For example,
Given n = 3, your program should return all 5 unique BST's shown Given a binary tree, determine if it is a valid binary search tree
below. (BST).

1 3 3 2 1
\ / / / \ \ Assume a BST is defined as follows:
3 2 1 1 3 2
/ / \ \ The left subtree of a node contains only nodes with keys less than
2 1 2 3 the node's key.
The right subtree of a node contains only nodes with keys greater
than the node's key.
------------------------------ Both the left and right subtrees must also be binary search trees.
------------------------------
Unique Binary Search Trees
------------------------------
Given n, how many structurally unique BST's (binary search trees) Example 1:
that store values 1...n?
2
/ \
For example, 1 3
Given n = 3, there are a total of 5 unique BST's.
Binary tree [2,1,3], return true.

1 3 3 2 1
\ / / / \ \ Example 2:
3 2 1 1 3 2
/ / \ \ 1
2 1 2 3 / \
2 3

------------------------------ Binary tree [1,2,3], return false.


------------------------------
Interleaving String ------------------------------
------------------------------ ------------------------------
Recover Binary Search Tree
Given s1, s2, s3, find whether s3 is formed by the interleaving of ------------------------------
s1 and s2.
Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.


For example,
Given:
s1 = "aabcc", Note:
s2 = "dbbca", A solution using O(n) space is pretty straight forward. Could you
devise a constant space solution?

When s3 = "aadbbcbcac", return true. ------------------------------


When s3 = "aadbbbaccc", return false. ------------------------------
Same Tree
------------------------------ ------------------------------
------------------------------
Validate Binary Search Tree Given two binary trees, write a function to check if they are equal
or not.

Two binary trees are considered equal if they are structurally return its level order traversal as:
identical and the nodes have the same value.
[
------------------------------ [3],
------------------------------ [9,20],
Symmetric Tree [15,7]
------------------------------ ]
Given a binary tree, check whether it is a mirror of itself (ie,
symmetric around its center).
------------------------------
------------------------------
For example, this binary tree [1,2,2,3,4,4,3] is symmetric: Binary Tree Zigzag Level Order Traversal
------------------------------
1 Given a binary tree, return the zigzag level order traversal of its
/ \ nodes' values. (ie, from left to right, then right to left for the
2 2 next level and alternate between).
/ \ / \
3 4 4 3
For example:
Given binary tree [3,9,20,null,null,15,7],

But the following [1,2,2,null,3,null,3] is not: 3


/ \
1 9 20
/ \ / \
2 2 15 7
\ \
3 3

return its zigzag level order traversal as:

[
Note: [3],
Bonus points if you could solve it both recursively and iteratively. [20,9],
[15,7]
------------------------------ ]
------------------------------
Binary Tree Level Order Traversal
------------------------------ ------------------------------
Given a binary tree, return the level order traversal of its nodes' ------------------------------
values. (ie, from left to right, level by level). Maximum Depth of Binary Tree
------------------------------
Given a binary tree, find its maximum depth.
For example:
Given binary tree [3,9,20,null,null,15,7], The maximum depth is the number of nodes along the longest path from
the root node down to the farthest leaf node.
3 ------------------------------
/ \ ------------------------------
9 20 Construct Binary Tree from Preorder and Inorder Traversal
/ \ ------------------------------
15 7 Given preorder and inorder traversal of a tree, construct the binary

tree. Given a singly linked list where elements are sorted in ascending
order, convert it to a height balanced BST.
Note: ------------------------------
You may assume that duplicates do not exist in the tree. ------------------------------
Balanced Binary Tree
------------------------------ ------------------------------
------------------------------ Given a binary tree, determine if it is height-balanced.
Construct Binary Tree from Inorder and Postorder Traversal
------------------------------
Given inorder and postorder traversal of a tree, construct the
binary tree. For this problem, a height-balanced binary tree is defined as a
binary tree in which the depth of the two subtrees of every node
Note: never differ by more than 1.
You may assume that duplicates do not exist in the tree.
------------------------------
------------------------------ ------------------------------
------------------------------ Minimum Depth of Binary Tree
Binary Tree Level Order Traversal II ------------------------------
------------------------------ Given a binary tree, find its minimum depth.
Given a binary tree, return the bottom-up level order traversal of
its nodes' values. (ie, from left to right, level by level from leaf The minimum depth is the number of nodes along the shortest path
to root). from the root node down to the nearest leaf node.
------------------------------
------------------------------
For example: Path Sum
Given binary tree [3,9,20,null,null,15,7], ------------------------------

3 Given a binary tree and a sum, determine if the tree has a root-to-
/ \ leaf path such that adding up all the values along the path equals
9 20 the given sum.
/ \
15 7
For example:
Given the below binary tree and sum = 22,

return its bottom-up level order traversal as: 5


/ \
[ 4 8
[15,7], / / \
[9,20], 11 13 4
[3] / \ \
] 7 2 1

------------------------------
------------------------------ return true, as there exist a root-to-leaf path 5->4->11->2 which
Convert Sorted Array to Binary Search Tree sum is 22.
------------------------------ ------------------------------
Given an array where elements are sorted in ascending order, convert ------------------------------
it to a height balanced BST. Path Sum II
------------------------------ ------------------------------
------------------------------
Convert Sorted List to Binary Search Tree Given a binary tree and a sum, find all root-to-leaf paths where
------------------------------ each path's sum equals the given sum.
\
6
For example:
Given the below binary tree and sum = 22,
click to show hints.
5
/ \ Hints:
4 8 If you notice carefully in the flattened tree, each node's right
/ / \ child points to the next node of a pre-order traversal.
11 13 4
/ \ / \ ------------------------------
7 2 5 1 ------------------------------
Distinct Subsequences
------------------------------

return Given a string S and a string T, count the number of distinct


subsequences of T in S.
[
[5,4,11,2],
[5,8,4,5]
] 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).
Flatten Binary Tree to Linked List
------------------------------

Given a binary tree, flatten it to a linked list in-place. Here is an example:


S = "rabbbit", T = "rabbit"

For example, Return 3.


Given
------------------------------
1 ------------------------------
/ \ Populating Next Right Pointers in Each Node
2 5 ------------------------------
/ \ \
3 4 6 Given a binary tree

struct TreeLinkNode {
TreeLinkNode *left;
The flattened tree should look like: TreeLinkNode *right;
TreeLinkNode *next;
1 }
\
2
\
3 Populate each next pointer to point to its next right node. If there
\ is no next right node, the next pointer should be set to NULL.
4
\ Initially, all next pointers are set to NULL.
5

Note: 1 -> NULL


/ \
You may only use constant extra space. 2 -> 3 -> NULL
You may assume that it is a perfect binary tree (ie, all leaves are / \ \
at the same level, and every parent has two children). 4-> 5 -> 7 -> NULL

------------------------------
------------------------------
For example, Pascal's Triangle
Given the following perfect binary tree, ------------------------------
Given numRows, generate the first numRows of Pascal's triangle.
1
/ \
2 3 For example, given numRows = 5,
/ \ / \ Return
4 5 6 7
[
[1],
[1,1],
After calling your function, the tree should look like: [1,2,1],
[1,3,3,1],
1 -> NULL [1,4,6,4,1]
/ \ ]
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL ------------------------------
------------------------------
Pascal's Triangle II
------------------------------ ------------------------------
------------------------------ Given an index k, return the kth row of the Pascal's triangle.
Populating Next Right Pointers in Each Node II
------------------------------
Follow up for problem "Populating Next Right Pointers in Each Node". For example, given k = 3,
What if the given tree could be any binary tree? Would your previous Return [1,3,3,1].
solution still work?

Note:
You may only use constant extra space. Note:
Could you optimize your algorithm to use only O(k) extra space?

For example, ------------------------------


Given the following binary tree, ------------------------------
Triangle
1 ------------------------------
/ \ Given a triangle, find the minimum path sum from top to bottom. Each
2 3 step you may move to adjacent numbers on the row below.
/ \ \
4 5 7
For example, given the following triangle

[
After calling your function, the tree should look like: [2],
[3,4], stock multiple times). However, you may not engage in multiple
[6,5,7], transactions at the same time (ie, you must sell the stock before
[4,1,8,3] you buy again).
] ------------------------------
------------------------------
Best Time to Buy and Sell Stock III
------------------------------
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = Say you have an array for which the ith element is the price of a
11). given stock on day i.

Design an algorithm to find the maximum profit. You may complete at


most two transactions.
Note:
Bonus point if you are able to do this using only O(n) extra space, Note:
where n is the total number of rows in the triangle. You may not engage in multiple transactions at the same time (ie,
you must sell the stock before you buy again).
------------------------------ ------------------------------
------------------------------ ------------------------------
Best Time to Buy and Sell Stock Binary Tree Maximum Path Sum
------------------------------ ------------------------------
Say you have an array for which the ith element is the price of a
given stock on day i. Given a binary tree, find the maximum path sum.

If you were only permitted to complete at most one transaction (ie,


buy one and sell one share of the stock), design an algorithm to For this problem, a path is defined as any sequence of nodes from
find the maximum profit. some starting node to any node in the tree along the parent-child
connections. The path must contain at least one node and does not
Example 1: need to go through the root.

Input: [7, 1, 5, 3, 6, 4]
Output: 5 For example:
Given the below binary tree,
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be
larger than buying price) 1
/ \
2 3

Example 2:

Input: [7, 6, 4, 3, 1] Return 6.


Output: 0
------------------------------
In this case, no transaction is done, i.e. max profit = 0. ------------------------------
Valid Palindrome
------------------------------
------------------------------
------------------------------ Given a string, determine if it is a palindrome, considering only
Best Time to Buy and Sell Stock II alphanumeric characters and ignoring cases.
------------------------------
Say you have an array for which the ith element is the price of a
given stock on day i.
For example,
Design an algorithm to find the maximum profit. You may complete as "A man, a plan, a canal: Panama" is a palindrome.
many transactions as you like (ie, buy one and sell one share of the "race a car" is not a palindrome.

Note: UPDATE (2017/1/20):


Have you consider that the string might be empty? This is a good The wordList parameter had been changed to a list of strings
question to ask during an interview. (instead of a set of strings). Please reload the code definition to
get the latest changes.
For the purpose of this problem, we define empty string as valid
palindrome. ------------------------------
------------------------------
------------------------------ Word Ladder
------------------------------ ------------------------------
Word Ladder II
------------------------------ Given two words (beginWord and endWord), and a dictionary's word
list, find the length of shortest transformation sequence from
Given two words (beginWord and endWord), and a dictionary's word beginWord to endWord, such that:
list, find all shortest transformation sequence(s) from beginWord to
endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that
Only one letter can be changed at a time beginWord is not a transformed word.
Each transformed word must exist in the word list. Note that
beginWord is not a transformed word.

For example,

For example,
Given:
beginWord = "hit"
Given: endWord = "cog"
beginWord = "hit" wordList = ["hot","dot","dog","lot","log","cog"]
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -
> "cog",
Return return its length 5.

[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"] Note:
]
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
Note: You may assume beginWord and endWord are non-empty and are not the
same.
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the UPDATE (2017/1/20):
same. The wordList parameter had been changed to a list of strings
(instead of a set of strings). Please reload the code definition to
get the latest changes.

------------------------------
------------------------------ For example,
Longest Consecutive Sequence
------------------------------ X X X X
X O O X
Given an unsorted array of integers, find the length of the longest X X O X
consecutive elements sequence. X O X X

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return After running your function, the board should be:
its length: 4.
X X X X
X X X X
Your algorithm should run in O(n) complexity. X X X X
X O X X
------------------------------
------------------------------
Sum Root to Leaf Numbers ------------------------------
------------------------------ ------------------------------
Given a binary tree containing digits from 0-9 only, each root-to- Palindrome Partitioning
leaf path could represent a number. ------------------------------
An example is the root-to-leaf path 1->2->3 which represents the
number 123. Given a string s, partition s such that every substring of the
partition is a palindrome.
Find the total sum of all root-to-leaf numbers.

For example, Return all possible palindrome partitioning of s.

1
/ \ For example, given s = "aab",
2 3
Return

[
The root-to-leaf path 1->2 represents the number 12. ["aa","b"],
The root-to-leaf path 1->3 represents the number 13. ["a","a","b"]
]

Return the sum = 12 + 13 = 25.


------------------------------
------------------------------ ------------------------------
------------------------------ Palindrome Partitioning II
Surrounded Regions ------------------------------
------------------------------
Given a string s, partition s such that every substring of the
Given a 2D board containing 'X' and 'O' (the letter O), capture all partition is a palindrome.
regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that Return the minimum cuts needed for a palindrome partitioning of s.
surrounded region.

For example, given s = "aab", ------------------------------


Return 1 since the palindrome partitioning ["aa","b"] could be ------------------------------
produced using 1 cut. Gas Station
------------------------------
------------------------------
------------------------------ There are N gas stations along a circular route, where the amount of
Clone Graph gas at station i is gas[i].
------------------------------

Clone an undirected graph. Each node in the graph contains a label


and a list of its neighbors. 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.

OJ's undirected graph serialization:


Return the starting gas station's index if you can travel around the
circuit once, otherwise return -1.
Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node Note:
label and each neighbor of the node. The solution is guaranteed to be unique.

------------------------------
------------------------------
Candy
As an example, consider the serialized graph {0,1,2#1,2#2,2}. ------------------------------

There are N children standing in a line. Each child is assigned a


rating value.
The graph has a total of three nodes, and therefore contains three
parts as separated by #.
You are giving candies to these children subjected to the following
First node is labeled as 0. Connect node 0 to both nodes 1 and 2. requirements:
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus
forming a self-cycle. Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?


Visually, the graph looks like the following:
------------------------------
1 ------------------------------
/ \ Single Number
/ \ ------------------------------
0 --- 2 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? ------------------------------
------------------------------
------------------------------ Word Break II
------------------------------ ------------------------------
Single Number II
------------------------------ Given a non-empty string s and a dictionary wordDict containing a
list of non-empty words, add spaces in s to construct a sentence
Given an array of integers, every element appears three times except where each word is a valid dictionary word. You may assume the
for one, which appears exactly once. Find that single one. dictionary does not contain duplicate words.

Note: Return all such possible sentences.


Your algorithm should have a linear runtime complexity. Could you
implement it without using extra memory?

------------------------------ For example, given


------------------------------ s = "catsanddog",
Copy List with Random Pointer dict = ["cat", "cats", "and", "sand", "dog"].
------------------------------

A linked list is given such that each node contains an additional


random pointer which could point to any node in the list or null. A solution is ["cats and dog", "cat sand dog"].

Return a deep copy of the list. 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
------------------------------ ------------------------------
------------------------------
Given a non-empty string s and a dictionary wordDict containing a Linked List Cycle
list of non-empty words, determine if s can be segmented into a ------------------------------
space-separated sequence of one or more dictionary words. You may
assume the dictionary does not contain duplicate words. Given a linked list, determine if it has a cycle in it.

For example, given


s = "leetcode", Follow up:
dict = ["leet", "code"]. Can you solve it without using extra space?

------------------------------
------------------------------
Return true because "leetcode" can be segmented as "leet code". Linked List Cycle II
------------------------------

Given a linked list, return the node where the cycle begins. If
UPDATE (2017/1/4): there is no cycle, return null.
The wordDict parameter had been changed to a list of strings
(instead of a set of strings). Please reload the code definition to
get the latest changes.
Note: Do not modify the linked list.

1
\
Follow up: 2
Can you solve it without using extra space? /
3
------------------------------
------------------------------
Reorder List
------------------------------ return [3,2,1].

Given a singly linked list L: L0→L1→…→Ln-1→Ln,


reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… Note: Recursive solution is trivial, could you do it iteratively?
------------------------------
------------------------------
You must do this in-place without altering the nodes' values. LRU Cache
------------------------------

For example, Design and implement a data structure for Least Recently Used (LRU)
Given {1,2,3,4}, reorder it to {1,4,2,3}. cache. It should support the following operations: get and put.

------------------------------
------------------------------
Binary Tree Preorder Traversal get(key) - Get the value (will always be positive) of the key if the
------------------------------ key exists in the cache, otherwise return -1.
Given a binary tree, return the preorder traversal of its nodes' put(key, value) - Set or insert the value if the key is not already
values. present. When the cache reached its capacity, it should invalidate
the least recently used item before inserting a new item.

For example:
Given binary tree {1,#,2,3}, Follow up:
Could you do both operations in O(1) time complexity?
1
\ Example:
2
/ LRUCache cache = new LRUCache( 2 /* capacity */ );
3
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
return [1,2,3]. cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
Note: Recursive solution is trivial, could you do it iteratively? cache.get(1); // returns -1 (not found)
------------------------------ cache.get(3); // returns 3
------------------------------ cache.get(4); // returns 4
Binary Tree Postorder Traversal
------------------------------
Given a binary tree, return the postorder traversal of its nodes' ------------------------------
values. ------------------------------
Insertion Sort List
------------------------------
For example: Sort a linked list using insertion sort.
Given binary tree {1,#,2,3}, ------------------------------
------------------------------
Sort List
------------------------------
Sort a linked list in O(n log n) time using constant space What constitutes a word?
complexity. A sequence of non-space characters constitutes a word.
------------------------------ Could the input string contain leading or trailing spaces?
------------------------------ Yes. However, your reversed string should not contain leading or
Max Points on a Line trailing spaces.
------------------------------ How about multiple spaces between two words?
Given n points on a 2D plane, find the maximum number of points that Reduce them to a single space in the reversed string.
lie on the same straight line.
------------------------------
------------------------------
Evaluate Reverse Polish Notation ------------------------------
------------------------------ ------------------------------
Maximum Product Subarray
Evaluate the value of an arithmetic expression in Reverse Polish ------------------------------
Notation.
Find the contiguous subarray within an array (containing at least
one number) which has the largest product.

Valid operators are +, -, *, /. Each operand may be an integer or


another expression.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

Some examples: ------------------------------


------------------------------
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 Find Minimum in Rotated Sorted Array
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 ------------------------------
Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.
------------------------------
------------------------------ (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Reverse Words in a String
------------------------------ Find the minimum element.

Given an input string, reverse the string word by word. You may assume no duplicate exists in the array.
------------------------------
------------------------------
Find Minimum in Rotated Sorted Array II
For example, ------------------------------
Given s = "the sky is blue",
return "blue is sky the". Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?


Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Suppose an array sorted in ascending order is rotated at some pivot
unknown to you beforehand.
click to show clarification.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Clarification:
Find the minimum element.

B: b1 → b2 → b3
The array may contain duplicates.
------------------------------ begin to intersect at node c1.
------------------------------
Min Stack Notes:
------------------------------
If the two linked lists have no intersection at all, return null.
Design a stack that supports push, pop, top, and retrieving the The linked lists must retain their original structure after the
minimum element in constant time. function returns.
You may assume there are no cycles anywhere in the entire linked
structure.
push(x) -- Push element x onto stack. Your code should preferably run in O(n) time and use only O(1)
memory.

pop() -- Removes the element on top of the stack.

Credits:Special thanks to @stellari for adding this problem and


top() -- Get the top element. creating all test cases.
------------------------------
------------------------------
getMin() -- Retrieve the minimum element in the stack. ------------------------------
Find Peak Element
------------------------------
A peak element is an element that is greater than its neighbors.

Example: Given an input array where num[i] ≠ num[i+1], find a peak element
and return its index.
MinStack minStack = new MinStack();
minStack.push(-2); The array may contain multiple peaks, in that case return the index
minStack.push(0); to any one of the peaks is fine.
minStack.push(-3);
minStack.getMin(); --> Returns -3. You may imagine that num[-1] = num[n] = -∞.
minStack.pop();
minStack.top(); --> Returns 0. For example, in array [1, 2, 3, 1], 3 is a peak element and your
minStack.getMin(); --> Returns -2. function should return the index number 2.

click to show spoilers.


------------------------------
------------------------------ Note:
------------------------------ Your solution should be in logarithmic complexity.
------------------------------
------------------------------
------------------------------ Credits:Special thanks to @ts for adding this problem and creating
Intersection of Two Linked Lists all test cases.
------------------------------ ------------------------------
Write a program to find the node at which the intersection of two ------------------------------
singly linked lists begins. ------------------------------
Maximum Gap
For example, the following two linked lists: ------------------------------
Given an unsorted array, find the maximum difference between the
A: a1 → a2 successive elements in its sorted form.

c1 → c2 → c3 Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.
Credits:Special thanks to @Shangrila for adding this problem and
You may assume all elements in the array are non-negative integers creating all test cases.
and fit in the 32-bit signed integer range. ------------------------------
------------------------------
Credits:Special thanks to @porker2008 for adding this problem and Two Sum II - Input array is sorted
creating all test cases. ------------------------------
------------------------------ Given an array of integers that is already sorted in ascending
------------------------------ order, find two numbers such that they add up to a specific target
Compare Version Numbers number.
------------------------------
Compare two version numbers version1 and version2. The function twoSum should return indices of the two numbers such
If version1 &gt; version2 return 1, if version1 &lt; version2 return that they add up to the target, where index1 must be less than
-1, otherwise return 0. index2. Please note that your returned answers (both index1 and
index2) are not zero-based.
You may assume that the version strings are non-empty and contain
only digits and the . character. You may assume that each input would have exactly one solution and
The . character does not represent a decimal point and is used to you may not use the same element twice.
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- Input: numbers={2, 7, 11, 15}, target=9
level revision. Output: index1=1, index2=2

Here is an example of version numbers ordering: ------------------------------


0.1 &lt; 1.1 &lt; 1.2 &lt; 13.37 ------------------------------
Excel Sheet Column Title
Credits:Special thanks to @ts for adding this problem and creating ------------------------------
all test cases. Given a positive integer, return its corresponding column title as
------------------------------ appear in an Excel sheet.
------------------------------
Fraction to Recurring Decimal For example:
------------------------------
Given two integers representing the numerator and denominator of a 1 -> A
fraction, return the fraction in string format. 2 -> B
3 -> C
If the fractional part is repeating, enclose the repeating part in ...
parentheses. 26 -> Z
27 -> AA
For example, 28 -> AB

Given numerator = 1, denominator = 2, return "0.5". Credits:Special thanks to @ifanchu for adding this problem and
Given numerator = 2, denominator = 1, return "2". creating all test cases.
Given numerator = 2, denominator = 3, return "0.(6)". ------------------------------
------------------------------
Majority Element
------------------------------
Given an array of size n, find the majority element. The majority
No scary math, just apply elementary math knowledge. Still element is the element that appears more than &lfloor; n/2 &rfloor;
remember how to perform a long division? times.
Try a long division on 4/9, the repeating part is obvious. Now try
4/333. Do you see a pattern? You may assume that the array is non-empty and the majority element
Be wary of edge cases! List out as many test cases as you can always exist in the array.
think of and test your code thoroughly.
Credits:Special thanks to @ts for adding this problem and creating

all test cases. .dungeon th, .dungeon td {


------------------------------ text-align: center;
------------------------------ height: 70px;
------------------------------ width: 70px;
Excel Sheet Column Number }
------------------------------
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its The demons had captured the princess (P) and imprisoned her in the
corresponding column number. 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
For example: positioned in the top-left room and must fight his way through the
A -&gt; 1 dungeon to rescue the princess.
B -&gt; 2 The knight has an initial health point represented by a positive
C -&gt; 3 integer. If at any point his health point drops to 0 or below, he
... dies immediately.
Z -&gt; 26 Some of the rooms are guarded by demons, so the knight loses health
AA -&gt; 27 (negative integers) upon entering these rooms;
AB -&gt; 28 other rooms are either empty (0's) or contain magic orbs that
increase the knight's health (positive integers).
Credits:Special thanks to @ts for adding this problem and creating In order to reach the princess as quickly as possible, the knight
all test cases. decides to move only rightward or downward in each step.
------------------------------
------------------------------
Factorial Trailing Zeroes Write a function to determine the knight's minimum initial health so
------------------------------ that he is able to rescue the princess.
Given an integer n, return the number of trailing zeroes in n!. For example, given the dungeon below, the initial health of the
knight must be at least 7 if he follows the optimal path RIGHT->
Note: Your solution should be in logarithmic time complexity. RIGHT -> DOWN -> DOWN.

Credits:Special thanks to @ts for adding this problem and creating


all test cases.
------------------------------ -2 (K)
------------------------------ -3
Binary Search Tree Iterator 3
------------------------------
Implement an iterator over a binary search tree (BST). Your iterator
will be initialized with the root node of a BST. -5
-10
Calling next() will return the next smallest number in the BST. 1

Note: next() and hasNext() should run in average O(1) time and uses
O(h) memory, where h is the height of the tree. 10
30
Credits:Special thanks to @ts for adding this problem and creating -5 (P)
all test cases.
------------------------------
------------------------------
Dungeon Game
------------------------------
Notes:
table.dungeon, .dungeon th, .dungeon td {
border:3px solid black; The knight's health has no upper bound.
} Any room can contain threats or power-ups, even the first room the
knight enters and the bottom-right room where the princess is
imprisoned. you must sell the stock before you buy again).

Credits:Special thanks to @Freezen for adding this problem and


creating all test cases.
Credits:Special thanks to @stellari for adding this problem and ------------------------------
creating all test cases. ------------------------------
------------------------------ Rotate Array
------------------------------ ------------------------------
Largest Number Rotate an array of n elements to the right by k steps.
------------------------------ For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is
Given a list of non negative integers, arrange them such that they rotated to [5,6,7,1,2,3,4].
form the largest number.
Note:
For example, given [3, 30, 34, 5, 9], the largest formed number is Try to come up as many solutions as you can, there are at least 3
9534330. different ways to solve this problem.

Note: The result may be very large, so you need to return a string
instead of an integer. [show hint]
Hint:
Credits:Special thanks to @ts for adding this problem and creating Could you do it in-place with O(1) extra space?
all test cases.
------------------------------
------------------------------ Related problem: Reverse Words in a String II
------------------------------
Repeated DNA Sequences Credits:Special thanks to @Freezen for adding this problem and
------------------------------ creating all test cases.
------------------------------
All DNA is composed of a series of nucleotides abbreviated as A, C, ------------------------------
G, and T, for example: "ACGAATTCCG". When studying DNA, it is Reverse Bits
sometimes useful to identify repeated sequences within the DNA. ------------------------------
Reverse bits of a given 32 bits unsigned integer.
Write a function to find all the 10-letter-long sequences
(substrings) that occur more than once in a DNA molecule. For example, given input 43261596 (represented in binary as
00000010100101000001111010011100), return 964176192 (represented in
binary as 00111001011110000010100101000000).
For example,

Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", Follow up:


If this function is called many times, how would you optimize it?
Return:
["AAAAACCCCC", "CCCCCAAAAA"].
Related problem: Reverse Integer
------------------------------
------------------------------ Credits:Special thanks to @ts for adding this problem and creating
Best Time to Buy and Sell Stock IV all test cases.
------------------------------ ------------------------------
Say you have an array for which the ith element is the price of a ------------------------------
given stock on day i. Number of 1 Bits
------------------------------
Design an algorithm to find the maximum profit. You may complete at Write a function that takes an unsigned integer and returns the
most k transactions. number of ’1' bits it has (also known as the Hamming weight).

Note: For example, the 32-bit integer ’11' has binary representation
You may not engage in multiple transactions at the same time (ie, 00000000000000000000000000001011, so the function should return 3.

Credits:Special thanks to @ts for adding this problem and creating Example 1:
all test cases. 11110110101100000000
------------------------------ Answer: 1
------------------------------ Example 2:
House Robber 11000110000010000011
------------------------------ Answer: 3
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only Credits:Special thanks to @mithmatt for adding this problem and
constraint stopping you from robbing each of them is that adjacent creating all test cases.
houses have security system connected and it will automatically ------------------------------
contact the police if two adjacent houses were broken into on the ------------------------------
same night. Bitwise AND of Numbers Range
------------------------------
Given a list of non-negative integers representing the amount of Given a range [m, n] where 0 <= m <= n <= 2147483647, return the
money of each house, determine the maximum amount of money you can bitwise AND of all numbers in this range, inclusive.
rob tonight without alerting the police.

Credits:Special thanks to @ifanchu for adding this problem and For example, given the range [5, 7], you should return 4.
creating all test cases. Also thanks to @ts for adding additional
test cases.
------------------------------ Credits:Special thanks to @amrsaqr for adding this problem and
------------------------------ creating all test cases.
Binary Tree Right Side View ------------------------------
------------------------------ ------------------------------
Given a binary tree, imagine yourself standing on the right side of Happy Number
it, return the values of the nodes you can see ordered from top to ------------------------------
bottom. Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process:


For example: Starting with any positive integer, replace the number by the sum of
Given the following binary tree, the squares of its digits, and repeat the process until the number
equals 1 (where it will stay), or it loops endlessly in a cycle
1 <--- which does not include 1. Those numbers for which this process ends
/ \ in 1 are happy numbers.
2 3 <---
\ \ Example:&nbsp;19 is a happy number
5 4 <---

12 + 92 = 82
82 + 22 = 68
You should return [1, 3, 4]. 62 + 82 = 100
12 + 02 + 02 = 1

Credits:Special thanks to @amrsaqr for adding this problem and


creating all test cases. Credits:Special thanks to @mithmatt and @ts for adding this problem
------------------------------ and creating all test cases.
------------------------------ ------------------------------
Number of Islands ------------------------------
------------------------------ Remove Linked List Elements
Given a 2d grid map of '1's (land) and '0's (water), count the ------------------------------
number of islands. An island is surrounded by water and is formed by Remove all elements from a linked list of integers that have value
connecting adjacent lands horizontally or vertically. You may assume val.
all four edges of the grid are all surrounded by water.
Example private boolean isPrime(int num) {
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 if (num <= 1) return false;
Return: 1 --> 2 --> 3 --> 4 --> 5 // Loop's ending condition is i * i <= num instead of i <=
sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
Credits:Special thanks to @mithmatt for adding this problem and for (int i = 2; i * i <= num; i++) {
creating all test cases. if (num % i == 0) return false;
------------------------------ }
------------------------------ return true;
Count Primes }
------------------------------
Description:
Count the number of prime numbers less than a non-negative number, The Sieve of Eratosthenes is one of the most efficient ways to
n. find all prime numbers up to n. But don't let that name scare you, I
promise that the concept is surprisingly simple.
Credits:Special thanks to @mithmatt for adding this problem and
creating all test cases.

Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve


Let's start with a isPrime function. To determine if a number is of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
prime, we need to check if it is not divisible by any number less
than n. The runtime complexity of isPrime function would be O(n) and
hence counting the total prime numbers up to n would be O(n2). Could We start off with a table of n numbers. Let's look at the first
we do better? number, 2. We know all multiples of 2 must not be primes, so we mark
them off as non-primes. Then we look at the next number, 3.
As we know the number must not be divisible by any number > n / 2, Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must
we can immediately cut the total iterations half by dividing only up not be primes, so we mark them off as well. Now we look at the next
to n / 2. Could we still do better? number, 4, which was already marked off. What does this tell you?
Should you mark off all multiples of 4 as well?
Let's write down all of 12's factors:
4 is not a prime because it is divisible by 2, which means all
2 × 6 = 12 multiples of 4 must also be divisible by 2 and were already marked
3 × 4 = 12 off. So we can skip 4 immediately and go to the next number, 5. Now,
4 × 3 = 12 all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5
6 × 2 = 12 = 25, ... can be marked off. There is a slight optimization here, we
do not need to start from 5 × 2 = 10. Where should we start marking
off?
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary.
Therefore, we only need to consider factors up to &radic;n because, In fact, we can mark off multiples of 5 starting at 5 × 5 = 25,
if n is divisible by some number p, then n = p × q and since p &le; because 5 × 2 = 10 was already marked off by multiple of 2,
q, we could derive that p &le; &radic;n. similarly 5 × 3 = 15 was already marked off by multiple of 3.
Therefore, if the current number is p, we can always mark off
Our total runtime has now improved to O(n1.5), which is slightly multiples of p starting at p2, then in increments of p: p2 + p, p2 +
better. Is there a faster approach? 2p, ... Now what should be the terminating loop condition?

It is easy to say that the terminating loop condition is p < n,


public int countPrimes(int n) { which is certainly correct but not efficient. Do you still remember
int count = 0; Hint #3?
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++; Yes, the terminating loop condition can be p < &radic;n, as all
} non-primes &ge; &radic;n must have already been marked off. When the
return count; loop terminates, all the numbers in the table that are non-marked
} are prime.

The Sieve of Eratosthenes uses an extra O(n) memory and its runtime ------------------------------
complexity is O(n log log n). For the more mathematically inclined Reverse a singly linked list.
readers, you can read more about its algorithm complexity on
Wikipedia. click to show more hints.

Hint:
public int countPrimes(int n) { A linked list can be reversed either iteratively or recursively.
boolean[] isPrime = new boolean[n]; Could you implement both?
for (int i = 2; i < n; i++) {
isPrime[i] = true; ------------------------------
} ------------------------------
// Loop's ending condition is i * i < n instead of i < sqrt(n) Course Schedule
// to avoid repeatedly calling an expensive function sqrt(). ------------------------------
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue; There are a total of n courses you have to take, labeled from 0 to n
for (int j = i * i; j < n; j += i) { - 1.
isPrime[j] = false;
} Some courses may have prerequisites, for example to take course 0
} you have to first take course 1, which is expressed as a pair: [0,1]
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++; Given the total number of courses and a list of prerequisite pairs,
} is it possible for you to finish all courses?
return count;
}
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should
------------------------------ have finished course 0. So it is possible.
------------------------------
Isomorphic Strings 2, [[1,0],[0,1]]
------------------------------ There are a total of 2 courses to take. To take course 1 you should
Given two strings s and t, determine if they are isomorphic. have finished course 0, and to take course 0 you should also have
finished course 1. So it is impossible.
Two strings are isomorphic if the characters in s can be replaced to
get t. Note:

All occurrences of a character must be replaced with another The input prerequisites is a graph represented by a list of edges,
character while preserving the order of characters. No two not adjacency matrices. Read more about how a graph is represented.
characters may map to the same character but a character may map to You may assume that there are no duplicate edges in the input
itself. prerequisites.

For example,
Given "egg", "add", return true.
click to show more hints.
Given "foo", "bar", return false.
Hints:
Given "paper", "title", return true.
This problem is equivalent to finding if a cycle exists in a
Note: directed graph. If a cycle exists, no topological ordering exists
You may assume both s and t have the same length. and therefore it will be impossible to take all courses.
------------------------------ Topological Sort via DFS - A great video tutorial (21 minutes) on
------------------------------ Coursera explaining the basic concepts of Topological Sort.
Reverse Linked List Topological sort could also be done via BFS.
There may be multiple correct orders, you just need to return one of
------------------------------ them. If it is impossible to finish all courses, return an empty
------------------------------ array.
Implement Trie (Prefix Tree)
------------------------------
For example:
Implement a trie with insert, search, and startsWith methods. 2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should
have finished course 0. So the correct course order is [0,1]

Note: 4, [[1,0],[2,0],[3,1],[3,2]]
You may assume that all inputs are consist of lowercase letters a-z. There are a total of 4 courses to take. To take course 3 you should
have finished both courses 1 and 2. Both courses 1 and 2 should be
------------------------------ taken after you finished course 0. So one correct course order is
------------------------------ [0,1,2,3]. Another correct ordering is[0,2,1,3].
Minimum Size Subarray Sum
------------------------------ Note:

Given an array of n positive integers and a positive integer s, find The input prerequisites is a graph represented by a list of edges,
the minimal length of a contiguous subarray of which the sum ≥ s. If not adjacency matrices. Read more about how a graph is represented.
there isn't one, return 0 instead. You may assume that there are no duplicate edges in the input
prerequisites.

For example, given the array [2,3,1,2,4,3] and s = 7,


the subarray [4,3] has the minimal length under the problem
constraint. click to show more hints.

Hints:
click to show more practice.
This problem is equivalent to finding the topological order in a
More practice: directed graph. If a cycle exists, no topological ordering exists
and therefore it will be impossible to take all courses.
If you have figured out the O(n) solution, try coding another Topological Sort via DFS - A great video tutorial (21 minutes) on
solution of which the time complexity is O(n log n). Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.

Credits:Special thanks to @Freezen for adding this problem and


creating all test cases. ------------------------------
------------------------------ ------------------------------
------------------------------ Add and Search Word - Data structure design
Course Schedule II ------------------------------
------------------------------
Design a data structure that supports the following two operations:
There are a total of n courses you have to take, labeled from 0 to n
- 1.
void addWord(word)
Some courses may have prerequisites, for example to take course 0 bool search(word)
you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, search(word) can search a literal word or a regular expression
return the ordering of courses you should take to finish all string containing only letters a-z or .. A . means it can represent
courses. any one letter.

Note:
You may assume that all inputs are consist of lowercase letters a-z.
For example:

addWord("bad") click to show hint.


addWord("dad")
addWord("mad") You would need to optimize your backtracking to pass the larger
search("pad") -> false test. Could you stop backtracking earlier?
search("bad") -> true
search(".ad") -> true If the current candidate does not exist in all words' prefix, you
search("b..") -> true 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
Note: (Prefix Tree) first.
You may assume that all words are consist of lowercase letters a-z.
------------------------------
------------------------------
click to show hint. House Robber II
------------------------------
You should be familiar with how a Trie works. If not, please work on Note: This is an extension of House Robber.
this problem: Implement Trie (Prefix Tree) first.
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
Word Search II 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.
Given a 2D board and a list of words from the dictionary, find all
words in the board. Given a list of non-negative integers representing the amount of
money of each house, determine the maximum amount of money you can
rob tonight without alerting the police.
Each word must be constructed from letters of sequentially adjacent
cell, where "adjacent" cells are those horizontally or vertically Credits:Special thanks to @Freezen for adding this problem and
neighboring. The same letter cell may not be used more than once in creating all test cases.
a word. ------------------------------
------------------------------
Shortest Palindrome
------------------------------
For example,
Given words = ["oath","pea","eat","rain"] and board = Given a string S, you are allowed to convert it to a palindrome by
adding characters in front of it. Find and return the shortest
[ palindrome you can find by performing this transformation.
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'], For example:
['i','f','l','v'] Given "aacecaaa", return "aaacecaaa".
] Given "abcd", return "dcbabcd".

Credits:Special thanks to @ifanchu for adding this problem and


Return ["eat","oath"]. creating all test cases. Thanks to @Freezen for additional test
cases.
------------------------------
------------------------------
Kth Largest Element in an Array ------------------------------
------------------------------ The Skyline Problem
Find the kth largest element in an unsorted array. Note that it is ------------------------------
the kth largest element in the sorted order, not the kth distinct A city's skyline is the outer contour of the silhouette formed by
element. all the buildings in that city when viewed from a distance. Now
suppose you are given the locations and height of all the buildings
For example, as shown on a cityscape photo (Figure A), write a program to output
Given [3,2,1,5,6,4] and k = 2, return 5. the skyline formed by these buildings collectively (Figure B).

Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.

Credits:Special thanks to @mithmatt for adding this problem and


creating all test cases.
------------------------------
------------------------------
Combination Sum III
------------------------------

Find all possible combinations of k numbers that add up to a number


n, given that only numbers from 1 to 9 can be used and each
combination should be a unique set of numbers. The geometric information of each building is represented by a
triplet of integers [Li, Ri, Hi], where Li and Ri are the x
coordinates of the left and right edge of the ith building,
respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri
Example 1: ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all
Input: k = 3, n = 7 buildings are perfect rectangles grounded on an absolutely flat
Output: surface at height 0.

[[1,2,4]] For instance, the dimensions of all buildings in Figure A are


recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24
8] ] .
Example 2:
Input: k = 3, n = 9 The output is a list of "key points" (red dots in Figure B) in the
Output: format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines
a skyline. A key point is the left endpoint of a horizontal line
[[1,2,6], [1,3,5], [2,3,4]] segment. Note that the last key point, where the rightmost building
ends, is merely used to mark the termination of the skyline, and
always has zero height. Also, the ground in between any two adjacent
buildings should be considered part of the skyline contour.
Credits:Special thanks to @mithmatt for adding this problem and
creating all test cases. For instance, the skyline in Figure B should be represented as:[ [2
------------------------------ 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].
------------------------------
Contains Duplicate Notes:
------------------------------
The number of buildings in any input list is guaranteed to be in
Given an array of integers, find if the array contains any the range [0, 10000].
duplicates. Your function should return true if any value appears at The input list is already sorted in ascending order by the left x
least twice in the array, and it should return false if every position Li.
element is distinct. The output list must be sorted by the x position.
There must be no consecutive horizontal lines of equal height in
------------------------------ the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5],

[12 7]...] is not acceptable; the three lines of height 5 should be Definition of a complete binary tree from Wikipedia:
merged into one in the final output as such: [...[2 3], [4 5], [12 In a complete binary tree every level, except possibly the last, is
7], ...] completely filled, and all nodes in the last level are as far left
as possible. It can have between 1 and 2h nodes inclusive at the
last level h.
------------------------------
Credits:Special thanks to @stellari for adding this problem, ------------------------------
creating these two awesome images and all test cases. Rectangle Area
------------------------------ ------------------------------
------------------------------ Find the total area covered by two rectilinear rectangles in a 2D
Contains Duplicate II plane.
------------------------------ Each rectangle is defined by its bottom left corner and top right
corner as shown in the figure.
Given an array of integers and an integer k, find out whether there
are two distinct indices i and j in the array such that nums[i] =
nums[j] and the absolute difference between i and j is at most k.

------------------------------ Assume that the total area is never beyond the maximum possible
------------------------------ value of int.
Contains Duplicate III
------------------------------
Credits:Special thanks to @mithmatt for adding this problem,
Given an array of integers, find out whether there are two distinct creating the above image and all test cases.
indices i and j in the array such that the absolute difference ------------------------------
between nums[i] and nums[j] is at most t and the absolute difference ------------------------------
between i and j is at most k. Basic Calculator
------------------------------
------------------------------ Implement a basic calculator to evaluate a simple expression string.
------------------------------
Maximal Square The expression string may contain open ( and closing parentheses ),
------------------------------ the plus + or minus sign -, non-negative integers and empty
spaces .
Given a 2D binary matrix filled with 0's and 1's, find the largest
square containing only 1's and return its area. You may assume that the given expression is always valid.

Some examples:
For example, given the following matrix:
"1 + 1" = 2
1 0 1 0 0 " 2-1 + 2 " = 3
1 0 1 1 1 "(1+(4+5+2)-3)+(6+8)" = 23
1 1 1 1 1
1 0 0 1 0

Return 4.
Note: Do not use the eval built-in library function.

Credits:Special thanks to @Freezen for adding this problem and ------------------------------


creating all test cases. ------------------------------
------------------------------ Implement Stack using Queues
------------------------------ ------------------------------
Count Complete Tree Nodes
------------------------------ Implement the following operations of a stack using queues.
Given a complete binary tree, count the number of nodes.
push(x) -- Push element x onto stack.
The expression string contains only non-negative integers, +, -,
*, / operators and empty spaces . The integer division should
pop() -- Removes the element on top of the stack. truncate toward zero.

You may assume that the given expression is always valid.


top() -- Get the top element.
Some examples:

empty() -- Return whether the stack is empty. "3+2*2" = 7


" 3/2 " = 1
" 3+5 / 2 " = 5
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. Note: Do not use the eval built-in library function.
Depending on your language, queue may not be supported natively. You
may simulate a queue by using a list or deque (double-ended queue),
as long as you use only standard operations of a queue. Credits:Special thanks to @ts for adding this problem and creating
You may assume that all operations are valid (for example, no pop or all test cases.
top operations will be called on an empty stack). ------------------------------
------------------------------
Summary Ranges
------------------------------
Credits:Special thanks to @jianchao.li.fighter for adding this
problem and all test cases. Given a sorted integer array without duplicates, return the summary
------------------------------ of its ranges.
------------------------------
Invert Binary Tree
------------------------------ For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
Invert a binary tree.
4
/ \ Credits:Special thanks to @jianchao.li.fighter for adding this
2 7 problem and creating all test cases.
/ \ / \ ------------------------------
1 3 6 9 ------------------------------
Majority Element II
to ------------------------------
4 Given an integer array of size n, find all elements that appear more
/ \ than &lfloor; n/3 &rfloor; times. The algorithm should run in linear
7 2 time and in O(1) space.
/ \ / \
9 6 3 1
How many majority elements could it possibly have?
Trivia: Do you have a better hint? Suggest it!
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), ------------------------------
but you can’t invert a binary tree on a whiteboard so fuck off. ------------------------------
------------------------------ Kth Smallest Element in a BST
------------------------------ ------------------------------
Basic Calculator II Given a binary search tree, write a function kthSmallest to find the
------------------------------ kth smallest element in it.
Implement a basic calculator to evaluate a simple expression string.

Note: as long as you use only standard operations of a stack.


You may assume k is always valid, 1 ≤ k ≤ BST's total elements. You may assume that all operations are valid (for example, no pop or
peek operations will be called on an empty queue).
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? ------------------------------
Number of Digit One
------------------------------
Try to utilize the property of a BST. Given an integer n, count the total number of digit 1 appearing in
What if you could modify the BST node's structure? all non-negative integers less than or equal to n.
The optimal runtime complexity is O(height of BST).

For example:
Credits:Special thanks to @ts for adding this problem and creating Given n = 13,
all test cases. Return 6, because digit 1 occurred in the following numbers: 1, 10,
------------------------------ 11, 12, 13.
------------------------------
Power of Two
------------------------------
Beware of overflow.
Given an integer, write a function to determine if it is a power of
two. ------------------------------
------------------------------
Palindrome Linked List
Credits:Special thanks to @jianchao.li.fighter for adding this ------------------------------
problem and creating all test cases. Given a singly linked list, determine if it is a palindrome.
------------------------------
------------------------------ Follow up:
Implement Queue using Stacks Could you do it in O(n) time and O(1) space?
------------------------------ ------------------------------
------------------------------
Implement the following operations of a queue using stacks. Lowest Common Ancestor of a Binary Search Tree
------------------------------

push(x) -- Push element x to the back of queue. Given a binary search tree (BST), find the lowest common ancestor
(LCA) of two given nodes in the BST.

pop() -- Removes the element from in front of queue.

According to the definition of LCA on Wikipedia: “The lowest common


peek() -- Get the front element. ancestor is defined between two nodes v and w as the lowest node in
T that has both v and w as descendants (where we allow a node to be
a descendant of itself).”
empty() -- Return whether the queue is empty.

Notes: _______6______
/ \
You must use only standard operations of a stack -- which means only ___2__ ___8__
push to top, peek/pop from top, size, and is empty operations are / \ / \
valid. 0 _4 7 9
Depending on your language, stack may not be supported natively. You / \
may simulate a stack by using a list or deque (double-ended queue), 3 5
Given an array of n integers where n > 1, nums, return an array
output such that output[i] is equal to the product of all the
For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. elements of nums except nums[i].
Another example is LCA of nodes 2 and 4 is 2, since a node can be a
descendant of itself according to the LCA definition. Solve it without division and in O(n).
------------------------------
------------------------------ For example, given [1,2,3,4], return [24,12,8,6].
Lowest Common Ancestor of a Binary Tree
------------------------------ Follow up:
Could you solve it with constant space complexity? (Note: The output
Given a binary tree, find the lowest common ancestor (LCA) of two array does not count as extra space for the purpose of space
given nodes in the tree. complexity analysis.)
------------------------------
------------------------------
Sliding Window Maximum
According to the definition of LCA on Wikipedia: “The lowest common ------------------------------
ancestor is defined between two nodes v and w as the lowest node in Given an array nums, there is a sliding window of size k which is
T that has both v and w as descendants (where we allow a node to be moving from the very left of the array to the very right. You can
a descendant of itself).” only see the k numbers in the window. Each time the sliding window
moves right by one position.

For example,
_______3______ Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
/ \
___5__ ___1__
/ \ / \ Window position Max
6 _2 0 8 --------------- -----
/ \ [1 3 -1] -3 5 3 6 7 3
7 4 1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. 1 3 -1 -3 5 [3 6 7] 7
Another example is LCA of nodes 5 and 4 is 5, since a node can be a
descendant of itself according to the LCA definition.
------------------------------ Therefore, return the max sliding window as [3,3,5,5,6,7].
------------------------------
Delete Node in a Linked List Note:
------------------------------ You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for
non-empty array.
Write a function to delete a node (except the tail) in a singly
linked list, given only access to that node. Follow up:
Could you solve it in linear time?

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the How about using a data structure such as deque (double-ended
third node with value 3, the linked list should become 1 -> 2 -> 4 queue)?
after calling your function. The queue size need not be the same as the window’s size.
Remove redundant elements and the queue should store only elements
------------------------------ that need to be considered.
------------------------------
Product of Array Except Self ------------------------------
------------------------------ ------------------------------

Search a 2D Matrix II ------------------------------


------------------------------ ------------------------------
Write an efficient algorithm that searches for a value in an m x n Valid Anagram
matrix. This matrix has the following properties: ------------------------------
Given two strings s and t, write a function to determine if t is an
anagram of s.

Integers in each row are sorted in ascending from left to right. For example,
Integers in each column are sorted in ascending from top to bottom. s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
For example, You may assume the string contains only lowercase alphabets.

Consider the following matrix: Follow up:


What if the inputs contain unicode characters? How would you adapt
your solution to such case?
[ ------------------------------
[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] ------------------------------
] ------------------------------
------------------------------
------------------------------
Given target = 5, return true. ------------------------------
Given target = 20, return false. ------------------------------
------------------------------ ------------------------------
------------------------------ ------------------------------
Different Ways to Add Parentheses ------------------------------
------------------------------ ------------------------------
Given a string of numbers and operators, return all possible results ------------------------------
from computing all the different possible ways to group numbers and Binary Tree Paths
operators. The valid operators are +, - and *. ------------------------------

Example 1 Given a binary tree, return all root-to-leaf paths.


Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2 For example, given the following binary tree:
Output: [0, 2]

Example 2
Input: "2*3-4*5" 1
(2*(3-(4*5))) = -34 / \
((2*3)-(4*5)) = -14 2 3
((2*(3-4))*5) = -10 \
(2*((3-4)*5)) = -10 5
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]

Credits:Special thanks to @mithmatt for adding this problem and All root-to-leaf paths are:
creating all test cases. ["1->2->5", "1->3"]
The order of the result is not important. So in the above example,
[5, 3] is also correct.
Credits:Special thanks to @jianchao.li.fighter for adding this Your algorithm should run in linear runtime complexity. Could you
problem and creating all test cases. implement it using only constant space complexity?
------------------------------
------------------------------
Add Digits
------------------------------ Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases.
Given a non-negative integer num, repeatedly add all its digits ------------------------------
until the result has only one digit. ------------------------------
------------------------------
Ugly Number
------------------------------
For example:
Write a program to check whether a given number is an ugly number.

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2


has only one digit, return it.
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
Follow up: includes another prime factor 7.
Could you do it without any loop/recursion in O(1) runtime?

Note that 1 is typically treated as an ugly number.


A naive implementation of the above process is trivial. Could you
come up with other methods?
What are all the possible results? Credits:Special thanks to @jianchao.li.fighter for adding this
How do they occur, periodically or randomly? problem and creating all test cases.
You may find this Wikipedia article useful. ------------------------------
------------------------------
Ugly Number II
Credits:Special thanks to @jianchao.li.fighter for adding this ------------------------------
problem and creating all test cases.
------------------------------ Write a program to find the n-th ugly number.
------------------------------
------------------------------
Single Number III
------------------------------ 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
Given an array of numbers nums, in which exactly two elements appear of the first 10 ugly numbers.
only once and all the other elements appear exactly twice. Find the
two elements that appear only once.

Note that 1 is typically treated as an ugly number, and n does not


For example: exceed 1690.

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].


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
Note: effort on generating only the ugly ones.
An ugly number must be multiplied by either 2, 3, or 5 from a

smaller ugly number. For example, 123 and 123000.


The key is how to maintain the order of the ugly numbers. Try a Group the number by thousands (3 digits). You can write a helper
similar approach of merging from three sorted lists: L1, L2, and L3. function that takes a number less than 1000 and convert just that
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 chunk to words.
* 2, L2 * 3, L3 * 5). 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)
Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases. ------------------------------
------------------------------ ------------------------------
------------------------------ H-Index
------------------------------ ------------------------------
------------------------------
------------------------------ Given an array of citations (each citation is a non-negative
Missing Number integer) of a researcher, write a function to compute the
------------------------------ researcher's h-index.

Given an array containing n distinct numbers taken from 0, 1,


2, ..., n, find the one that is missing from the array.
According to the definition of h-index on Wikipedia: "A scientist
has index h if h of his/her N papers have at least h citations each,
For example, and the other N − h papers have no more than h citations each."
Given nums = [0, 1, 3] return 2.

For example, given citations = [3, 0, 6, 1, 5], which means the


Note: researcher has 5 papers in total and each of them had received 3, 0,
Your algorithm should run in linear runtime complexity. Could you 6, 1, 5 citations respectively. Since the researcher has 3 papers
implement it using only constant extra space complexity? with at least 3 citations each and the remaining two with no more
than 3 citations each, his h-index is 3.

Credits:Special thanks to @jianchao.li.fighter for adding this


problem and creating all test cases.
------------------------------ Note: If there are several possible values for h, the maximum one is
------------------------------ taken as the h-index.
------------------------------
------------------------------
------------------------------
Integer to English Words An easy approach is to sort the array first.
------------------------------ What are the possible values of h-index?
A faster approach is to use extra space.
Convert a non-negative integer to its english words representation.
Given input is guaranteed to be less than 231 - 1.
Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases.
For example, ------------------------------
------------------------------
123 -> "One Hundred Twenty Three" H-Index II
12345 -> "Twelve Thousand Three Hundred Forty Five" ------------------------------
1234567 -> "One Million Two Hundred Thirty Four Thousand Five
Hundred Sixty Seven" Follow up for H-Index: What if the citations array is sorted in
ascending order? Could you optimize your algorithm?

Did you see a pattern in dividing the number into chunk of words?
return all possibilities to add binary operators (not unary) +, -,
Expected runtime complexity is in O(log n) and the input is or * between the digits so they evaluate to the target value.
sorted.

------------------------------ Examples:
------------------------------ "123", 6 -> ["1+2+3", "1*2*3"]
------------------------------ "232", 8 -> ["2*3+2", "2+3*2"]
------------------------------ "105", 5 -> ["1*0+5","10-5"]
First Bad Version "00", 0 -> ["0+0", "0-0", "0*0"]
------------------------------ "3456237490", 9191 -> []

You are a product manager and currently leading a team to develop a


new product. Unfortunately, the latest version of your product fails Credits:Special thanks to @davidtan1890 for adding this problem and
the quality check. Since each version is developed based on the creating all test cases.
previous version, all the versions after a bad version are also bad. ------------------------------
------------------------------
Move Zeroes
------------------------------
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 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.

You are given an API bool isBadVersion(version) which will return


whether version is bad. Implement a function to find the first bad For example, given nums = [0, 1, 0, 3, 12], after calling your
version. You should minimize the number of calls to the API. function, nums should be [1, 3, 12, 0, 0].

Credits:Special thanks to @jianchao.li.fighter for adding this


problem and creating all test cases. Note:
------------------------------
------------------------------ You must do this in-place without making a copy of the array.
Perfect Squares Minimize the total number of operations.
------------------------------

Given a positive integer n, find the least number of perfect square


numbers (for example, 1, 4, 9, 16, ...) which sum to n. Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases.
------------------------------
------------------------------
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n Peeking Iterator
= 13, return 2 because 13 = 4 + 9. ------------------------------
Given an Iterator class interface with methods: next() and
hasNext(), design and implement a PeekingIterator that support the
Credits:Special thanks to @jianchao.li.fighter for adding this peek() operation -- it essentially peek() at the element that will
problem and creating all test cases. be returned by the next call to next().
------------------------------
------------------------------
------------------------------ Here is an example. Assume that the iterator is initialized to the
------------------------------ beginning of the list: [1, 2, 3].
Expression Add Operators
------------------------------ Call next() gets you 1, the first element in the list.

Given a string that contains only digits 0-9 and a target value, Now you call peek() and it returns 2, the next element. Calling

next() after that still return 2. mathematician John Horton Conway in 1970."

You call next() the final time and it returns 3, the last element.
Calling hasNext() after that should return false.
Given a board with m by n cells, each cell has an initial state live
(1) or dead (0). Each cell interacts with its eight neighbors
Think of "looking ahead". You want to cache the next element. (horizontal, vertical, diagonal) using the following four rules
Is one variable sufficient? Why or why not? (taken from the above Wikipedia article):
Test your design with call order of peek() before next() vs next()
before peek().
For a clean implementation, check out Google's guava library
source code.
Any live cell with fewer than two live neighbors dies, as if caused
by under-population.
Any live cell with two or three live neighbors lives on to the next
Follow up: How would you extend your design to be generic and work generation.
with all types, not just integer? Any live cell with more than three live neighbors dies, as if by
over-population..
Credits:Special thanks to @porker2008 for adding this problem and Any dead cell with exactly three live neighbors becomes a live cell,
creating all test cases. as if by reproduction.
------------------------------
------------------------------
------------------------------
------------------------------
Find the Duplicate Number Write a function to compute the next state (after one update) of the
------------------------------ board given its current state.

Given an array nums containing n + 1 integers where each integer is


between 1 and n (inclusive), prove that at least one duplicate Follow up:
number must exist. Assume that there is only one duplicate number,
find the duplicate one. Could you solve it in-place? Remember that the board needs to be
updated at the same time: You cannot update some cells first and
then use their updated values to update other cells.
In this question, we represent the board using a 2D array. In
Note: principle, the board is infinite, which would cause problems when
the active area encroaches the border of the array. How would you
You must not modify the array (assume the array is read only). address these problems?
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. Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases.
------------------------------
------------------------------
Credits:Special thanks to @jianchao.li.fighter for adding this Word Pattern
problem and creating all test cases. ------------------------------
------------------------------ Given a pattern and a string str, find if str follows the same
------------------------------ pattern.
------------------------------ Here follow means a full match, such that there is a bijection
Game of Life between a letter in pattern and a non-empty word in str.
------------------------------
Examples:
According to the Wikipedia's article: "The Game of Life, also known
simply as Life, is a cellular automaton devised by the British pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false. Examples:
pattern = "aaaa", str = "dog cat cat dog" should return false. [2,3,4] , the median is 3
pattern = "abba", str = "dog dog dog dog" should return false. [2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

Notes:
You may assume pattern contains only lowercase letters, and str void addNum(int num) - Add a integer number from the data stream to
contains lowercase letters separated by a single space. the data structure.
double findMedian() - Return the median of all elements so far.

Credits:Special thanks to @minglotus6 for adding this problem and


creating all test cases.
------------------------------ For example:
------------------------------
------------------------------ addNum(1)
Nim Game addNum(2)
------------------------------ findMedian() -> 1.5
addNum(3)
You are playing the following Nim Game with your friend: There is a findMedian() -> 2
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. Credits:Special thanks to @Louis1992 for adding this problem and
creating all test cases.
------------------------------
------------------------------
Both of you are very clever and have optimal strategies for the ------------------------------
game. Write a function to determine whether you can win the game Serialize and Deserialize Binary Tree
given the number of stones in the heap. ------------------------------
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
For example, if there are 4 stones in the heap, then you will never reconstructed later in the same or another computer environment.
win the game: no matter 1, 2, or 3 stones you remove, the last stone
will always be removed by your friend. Design an algorithm to serialize and deserialize a binary tree.
There is no restriction on how your serialization/deserialization
algorithm should work. You just need to ensure that a binary tree
can be serialized to a string and this string can be deserialized to
If there are 5 stones in the heap, could you figure out a way to the original tree structure.
remove the stones such that you will always be the winner?

For example, you may serialize the following tree


Credits:Special thanks to @jianchao.li.fighter for adding this
problem and creating all test cases. 1
------------------------------ / \
------------------------------ 2 3
------------------------------ / \
------------------------------ 4 5
Find Median from Data Stream
------------------------------ as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ
Median is the middle value in an ordered integer list. If the size serializes a binary tree. You do not necessarily need to follow this
of the list is even, there is no middle value. So the median is the format, so please be creative and come up with different approaches
mean of the two middle value. yourself.

Longest Increasing Subsequence


------------------------------

Note: Do not use class member/global/static variables to store Given an unsorted array of integers, find the length of longest
states. Your serialize and deserialize algorithms should be increasing subsequence.
stateless.

For example,
Credits:Special thanks to @Louis1992 for adding this problem and Given [10, 9, 2, 5, 3, 7, 101, 18],
creating all test cases. The longest increasing subsequence is [2, 3, 7, 101], therefore the
------------------------------ length is 4. Note that there may be more than one LIS combination,
------------------------------ it is only necessary for you to return the length.
------------------------------
Bulls and Cows
------------------------------ Your algorithm should run in O(n2) complexity.
You are playing the following Bulls and Cows game with your friend:
You write down a number and ask your friend to guess what the number
is. Each time your friend makes a guess, you provide a hint that Follow up: Could you improve it to O(n log n) time complexity?
indicates how many digits in said guess match your secret number
exactly in both digit and position (called "bulls") and how many Credits:Special thanks to @pbrother for adding this problem and
digits match the secret number but locate in the wrong position creating all test cases.
(called "cows"). Your friend will use successive guesses and hints ------------------------------
to eventually derive the secret number. ------------------------------
Remove Invalid Parentheses
------------------------------
For example:
Remove the minimum number of invalid parentheses in order to make
Secret number: "1807" the input string valid. Return all possible results.
Friend's guess: "7810"
Note: The input string may contain letters other than the
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.) parentheses ( and ).

Write a function to return a hint according to the secret number and


friend's guess, use A to indicate the bulls and B to indicate the Examples:
cows. In the above example, your function should return "1A3B".
"()())()" -> ["()()()", "(())()"]
Please note that both secret number and friend's guess may contain "(a)())()" -> ["(a)()()", "(a())()"]
duplicate digits, for example: ")(" -> [""]

Secret number: "1123"


Friend's guess: "0111"
Credits:Special thanks to @hpplayer for adding this problem and
In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd creating all test cases.
1 is a cow, and your function should return "1A1B". ------------------------------
------------------------------
------------------------------
You may assume that the secret number and your friend's guess only Range Sum Query - Immutable
contain digits, and their lengths are always equal. ------------------------------
Given an integer array nums, find the sum of the elements between
Credits:Special thanks to @jeantimex for adding this problem and indices i and j (i &le; j), inclusive.
creating all test cases.
------------------------------ Example:
------------------------------
Given nums = [-2, 0, 3, -5, 2, -1] Additive Number
------------------------------
sumRange(0, 2) -> 1 Additive number is a string whose digits can form additive sequence.
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3 A valid additive sequence should contain at least three numbers.
Except for the first two numbers, each subsequent number in the
sequence must be the sum of the preceding two.

Note:
For example:
You may assume that the array does not change. "112358" is an additive number because the digits can form an
There are many calls to sumRange function. additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199" is also an additive number, the additive sequence is: 1,
------------------------------ 99, 100, 199.
------------------------------ 1 + 99 = 100, 99 + 100 = 199
Range Sum Query 2D - Immutable
------------------------------
Given a 2D matrix matrix, find the sum of the elements inside the
rectangle defined by its upper left corner (row1, col1) and lower Note: Numbers in the additive sequence cannot have leading zeros, so
right corner (row2, col2). sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits '0'-'9', write a function to


The above rectangle (with the red border) is defined by (row1, col1) determine if it's an additive number.
= (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Follow up:
Example: How would you handle overflow for very large input integers?

Given matrix = [
[3, 0, 1, 4, 2], Credits:Special thanks to @jeantimex for adding this problem and
[5, 6, 3, 2, 1], creating all test cases.
[1, 2, 0, 1, 5], ------------------------------
[4, 1, 0, 1, 7], ------------------------------
[1, 0, 3, 0, 5] Range Sum Query - Mutable
] ------------------------------
Given an integer array nums, find the sum of the elements between
sumRegion(2, 1, 4, 3) -> 8 indices i and j (i &le; j), inclusive.
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12 The update(i, val) function modifies nums by updating the element at
index i to val.

Example:
Note:
Given nums = [1, 3, 5]
You may assume that the matrix does not change.
There are many calls to sumRegion function. sumRange(0, 2) -> 9
You may assume that row1 &le; row2 and col1 &le; col2. update(1, 2)
sumRange(0, 2) -> 8

------------------------------
------------------------------
------------------------------ Note:

The array is only modifiable by the update function. Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
You may assume the number of calls to update and sumRange function
is distributed evenly.
0 1 2
\ | /
------------------------------ 3
------------------------------ |
------------------------------ 4
Minimum Height Trees |
------------------------------ 5

For a undirected graph with tree characteristics, we can choose


any node as the root. The result graph is then a rooted tree. Among return [3, 4]
all possible rooted trees, those with minimum height are called
minimum height trees (MHTs).
Given such a graph, write a function to find all the MHTs and How many MHTs can a graph have at most?
return a list of their root labels.

Note:
Format
The graph contains n nodes which are labeled from 0 to n - 1.
You will be given the number n and a list of undirected edges (1) According to the definition
(each edge is a pair of labels). of tree on Wikipedia: “a tree is an undirected graph in which
any two vertices are connected by
exactly one path. In other words, any connected graph without
You can assume that no duplicate edges will appear in edges. Since simple cycles is a tree.”
all edges are
undirected, [0, 1] is the same as [1, 0] and thus will not
appear together in (2) The height of a rooted tree is the number of edges on the
edges. longest downward path between the root and a
leaf.

Example 1:
Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]] ------------------------------
------------------------------
------------------------------
Burst Balloons
0 ------------------------------
|
1 Given n balloons, indexed from 0 to n-1. Each balloon is painted
/ \ with a
2 3 number on it represented by array nums.

You are asked to burst all the balloons. If the you burst
return [1] balloon i you will get nums[left] * nums[i] * nums[right] coins.
Here left
and right are adjacent indices of i. After the burst, the left
and right
Example 2: then becomes adjacent.
Credits:Special thanks to @dietpepsi for adding this problem and
Find the maximum coins you can collect by bursting the balloons creating all test cases.
wisely. ------------------------------
------------------------------
------------------------------
Note: Count of Smaller Numbers After Self
(1) You may imagine nums[-1] = nums[n] = 1. They are not real ------------------------------
therefore you can not burst them.
(2) 0 &le; n &le; 500, 0 &le; nums[i] &le; 100 You are given an integer array nums and you have to return a new
counts array.
The counts array has the property where counts[i] is
the number of smaller elements to the right of nums[i].

Example:
Example:

Given [3, 1, 5, 8]
Given nums = [5, 2, 6, 1]

Return 167 To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] To the right of 1 there is 0 smaller element.
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167

Credits:Special thanks to @dietpepsi for adding this problem and Return the array [2, 1, 1, 0].
creating all test cases.
------------------------------ ------------------------------
------------------------------ ------------------------------
Super Ugly Number Remove Duplicate Letters
------------------------------ ------------------------------

Write a program to find the nth super ugly number. Given a string which contains only lowercase letters, remove
duplicate letters so that every letter appear once and only once.
You must make sure your result is the smallest in lexicographical
order among all possible results.
Super ugly numbers are positive numbers whose all prime factors
are in the given prime list
primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19,
26, 28, 32] Example:
is the sequence of the first 12 super ugly numbers given primes
= [2, 7, 13, 19] of size 4.
Given "bcabc"
Return "abc"

Note:
(1) 1 is a super ugly number for any given primes. Given "cbacdcbc"
(2) The given numbers in primes are in ascending order. Return "acdb"
(3) 0 < k &le; 100, 0 < n &le; 106, 0 < primes[i] < 1000.
(4) The nth super ugly number is guaranteed to fit in a 32-bit
signed integer. Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
------------------------------

------------------------------
------------------------------ Example:
Maximum Product of Word Lengths
------------------------------ Given n = 3.
At first, the three bulbs are [off, off, off].
Given a string array words, find the maximum value of After first round, the three bulbs are [on, on, on].
length(word[i]) * length(word[j]) where the two words do not share After second round, the three bulbs are [on, off, on].
common letters. After third round, the three bulbs are [on, off, off].
You may assume that each word will contain only lower case So you should return 1, because there is only one bulb is on.
letters.
If no such two words exist, return 0. ------------------------------
------------------------------
------------------------------
Create Maximum Number
Example 1: ------------------------------

Given two arrays of length m and n with digits 0-9 representing


Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] two numbers.
Return 16 Create the maximum number of length k <= m + n from digits of
The two words can be "abcw", "xtfn". the two. The relative order of the digits
from the same array must be preserved. Return an array of the k
digits. You should try to optimize your time and space complexity.
Example 2:

Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] Example 1:


Return 4
The two words can be "ab", "cd".
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
Example 3: k = 5
return [9, 8, 6, 5, 3]

Given ["a", "aa", "aaa", "aaaa"]


Return 0 Example 2:
No such pair of words.

nums1 = [6, 7]
Credits:Special thanks to @dietpepsi for adding this problem and nums2 = [6, 0, 4]
creating all test cases. k = 5
------------------------------ return [6, 7, 6, 0, 4]
------------------------------
Bulb Switcher
------------------------------ Example 3:

There are n bulbs that are initially off. You first turn on all the
bulbs. Then, you turn off every second bulb. On the third round, you nums1 = [3, 9]
toggle every third bulb (turning on if it's off or turning off if nums2 = [8, 9]
it's on). For the ith round, you toggle every i bulb. For the nth k = 3
round, you only toggle the last bulb. return [9, 8, 9]

Find how many bulbs are on after n rounds.


Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
------------------------------
------------------------------ Follow Up:
Coin Change Can you do it in O(n) time and/or in-place with O(1) extra
------------------------------ space?

You are given coins of different denominations and a total amount of


money amount. Write a function to compute the fewest number of coins Credits:Special thanks to @dietpepsi for adding this problem and
that you need to make up that amount. If that amount of money cannot creating all test cases.
be made up by any combination of the coins, return -1. ------------------------------
------------------------------
------------------------------
Power of Three
Example 1: ------------------------------
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1) Given an integer, write a function to determine if it is a power
of three.

Example 2: Follow up:


coins = [2], amount = 3 Could you do it without using any loop / recursion?
return -1.

Credits:Special thanks to @dietpepsi for adding this problem and


creating all test cases.
Note: ------------------------------
You may assume that you have an infinite number of each kind of ------------------------------
coin. Count of Range Sum
------------------------------

Credits:Special thanks to @jianchao.li.fighter for adding this Given an integer array nums, return the number of range sums
problem and creating all test cases. that lie in [lower, upper] inclusive.
------------------------------
------------------------------ Range sum S(i, j) is defined as the sum of the elements in nums
------------------------------ between indices i and
Wiggle Sort II j (i ≤ j), inclusive.
------------------------------

Given an unsorted array nums, reorder it such that


nums[0] < nums[1] > nums[2] < nums[3].... Note:
A naive algorithm of O(n2) is trivial. You MUST do better than
that.

Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, Example:
4, 1, 5, 1, 6]. Given nums = [-2, 5, -1], lower = -2, upper = 2,
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, Return 3.
3, 1, 3, 1, 2]. The three ranges are : [0, 0], [2, 2], [0, 2] and their
respective sums are: -2, -1, 2.

Note: Credits:Special thanks to @dietpepsi for adding this problem and


You may assume all input has valid answer. creating all test cases.
------------------------------
------------------------------

Odd Even Linked List nums = [


------------------------------ [3,4,5],
Given a singly linked list, group all odd nodes together followed by [3,2,6],
the even nodes. Please note here we are talking about the node [2,2,1]
number and not the value in the nodes. ]

You should try to do it in place. The program should run in O(1)


space complexity and O(nodes) time complexity.

Return 4
Example:
Given 1->2->3->4->5->NULL, The longest increasing path is [3, 4, 5, 6]. Moving diagonally is
return 1->3->5->2->4->NULL. not allowed.

Credits:Special thanks to @dietpepsi for adding this problem and


Note: creating all test cases.
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 ... Patching Array
------------------------------
Given a sorted positive integer array nums and an integer n, add/
Credits:Special thanks to @DjangoUnchained for adding this problem patch elements to the array such that any number in range [1, n]
and creating all test cases. inclusive can be formed by the sum of some elements in the array.
------------------------------ Return the minimum number of patches required.
------------------------------
Longest Increasing Path in a Matrix
------------------------------ Example 1:
Given an integer matrix, find the length of the longest increasing nums = [1, 3], n = 6
path. Return 1.

Combinations of nums are [1], [3], [1,3], which form possible sums
From each cell, you can either move to four directions: left, right, of: 1, 3, 4.
up or down. You may NOT move diagonally or move outside of the Now if we add/patch 2 to nums, the combinations are: [1], [2], [3],
boundary (i.e. wrap-around is not allowed). [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1,
6].
Example 1: So we only need 1 patch.

nums = [ Example 2:
[9,9,4], nums = [1, 5, 10], n = 20
[6,6,8], Return 2.
[2,1,1] The two patches can be [2, 4].
]
Example 3:
nums = [1, 2, 2], n = 5
Return 0.

Return 4 Credits:Special thanks to @dietpepsi for adding this problem and


creating all test cases.
The longest increasing path is [1, 2, 6, 9]. ------------------------------
------------------------------
Verify Preorder Serialization of a Binary Tree
Example 2: ------------------------------
One way to serialize a binary tree is to use pre-order traversal.
When we encounter a non-null node, we record the node's value. If it lexical order than ["JFK", "LGB"].
is a null node, we record using a sentinel value such as #. All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.

_9_
/ \
3 2
/ \/ \ Example 1:
4 # 6 1 tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"],
/ \ / \ / \ ["LHR", "SFO"]]
# # # # # # Return ["JFK", "MUC", "LHR", "SFO", "SJC"].

For example, the above binary tree can be serialized to the string Example 2:
"9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node. tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],
["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Given a string of comma separated values, verify whether it is a Another possible reconstruction is
correct preorder traversal serialization of a binary tree. Find an ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical
algorithm without reconstructing the tree. order.

Each comma separated value in the string must be either an integer


or a character '#' representing null pointer. Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
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: Increasing Triplet Subsequence
"9,3,4,#,#,1,#,#,2,#,6,#,#" ------------------------------
Return true
Example 2: Given an unsorted array return whether an increasing subsequence of
"1,#" length 3 exists or not in the array.
Return false
Example 3:
"9,#,#,1" Formally the function should:
Return false Return true if there exists i, j, k
such that arr[i] &lt; arr[j] &lt; arr[k] given 0 &le; i &lt; j &lt;
Credits:Special thanks to @dietpepsi for adding this problem and k &le; n-1
creating all test cases. else return false.
------------------------------
------------------------------
Reconstruct Itinerary
------------------------------ Your algorithm should run in O(n) time complexity and O(1) space
Given a list of airline tickets represented by pairs of departure complexity.
and arrival airports [from, to], reconstruct the itinerary in order.
All of the tickets belong to a man who departs from JFK. Thus, the
itinerary must begin with JFK. Examples:
Given [1, 2, 3, 4, 5],
return true.
Note:

If there are multiple valid itineraries, you should return the Given [5, 4, 3, 2, 1],
itinerary that has the smallest lexical order when read as a single return false.
string. For example, the itinerary ["JFK", "LGA"] has a smaller

└───┼>
Credits:Special thanks to @DjangoUnchained for adding this problem
and creating all test cases. Return true (self crossing)
------------------------------
------------------------------
Self Crossing
------------------------------ Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
You are given an array x of n positive numbers. You start at ------------------------------
point (0,0) and moves x[0] metres to the north, then x[1] metres to ------------------------------
the west, Palindrome Pairs
x[2] metres to the south, ------------------------------
x[3] metres to the east and so on. In other words, after each
move your direction changes Given a list of unique words, find all pairs of distinct indices
counter-clockwise. (i, j) in the given list, so that the concatenation of the two
words, i.e. words[i] + words[j] is a palindrome.

Write a one-pass algorithm with O(1) extra space to determine,


if your path crosses itself, or not.
Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
Example 1: The palindromes are ["battab", "tabbat"]

Given x = [2, 1, 1, 2],


┌───┐ 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"]

Return true (self crossing)


Credits:Special thanks to @dietpepsi for adding this problem and
creating all test cases.
------------------------------
------------------------------
Example 2: House Robber III
------------------------------
Given x = [1, 2, 3, 4],
┌──────┐ 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.
Return false (not self crossing)

Determine the maximum amount of money the thief can rob tonight
without alerting the police.
Example 3:

Given x = [1, 1, 1, 1], Example 1:


┌───┐
│ │ 3
/ \ creating all test cases.
2 3 ------------------------------
\ \ ------------------------------
3 1 ------------------------------
------------------------------
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Flatten Nested List Iterator
------------------------------
Given a nested list of integers, implement an iterator to flatten
Example 2: it.

3 Each element is either an integer, or a list -- whose elements may


/ \ also be integers or other lists.
4 5
/ \ \ Example 1:
1 3 1 Given the list [[1,1],2,[1,1]],

Maximum amount of money the thief can rob = 4 + 5 = 9. By calling next repeatedly until hasNext returns false, the order of
elements returned by next should be: [1,1,2,1,1].

Credits:Special thanks to @dietpepsi for adding this problem and


creating all test cases.
------------------------------ Example 2:
------------------------------ Given the list [1,[4,[6]]],
Counting Bits
------------------------------ By calling next repeatedly until hasNext returns false, the order of
Given a non negative integer number num. For every numbers i in the elements returned by next should be: [1,4,6].
range 0 &le; i &le; num calculate the number of 1's in their binary
representation and return them as an array.
------------------------------
------------------------------
Example: Power of Four
For num = 5 you should return [0,1,1,2,1,2]. ------------------------------

Given an integer (signed 32 bits), write a function to check whether


Follow up: it is a power of 4.

It is very easy to come up with a solution with run time Example:


O(n*sizeof(integer)). But can you do it in linear time O(n) / Given num = 16, return true.
possibly in a single pass? Given num = 5, return false.
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function
like __builtin_popcount in c++ or in any other language. Follow up: Could you solve it without loops/recursion?

Credits:Special thanks to @yukuairoy for adding this problem and


creating all test cases.
------------------------------
You should make use of what you have produced already. ------------------------------
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. Integer Break
And try to generate new range from previous. ------------------------------
Or does the odd/even status of the number help you in calculating
the number of 1s? Given a positive integer n, break it into the sum of at least two
positive integers and maximize the product of those integers. Return
the maximum product you can get.
Credits:Special thanks to @ syedee for adding this problem and

Top K Frequent Elements


------------------------------
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return
36 (10 = 3 + 3 + 4). Given a non-empty array of integers, return the k most frequent
elements.

For example,
Note: You may assume that n is not less than 2 and not larger than Given [1,1,1,2,2,3] and k = 2, return [1,2].
58.

Note:

There is a simple O(n) solution to this problem. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
You may check the breaking results of n ranging from 7 to 10 to Your algorithm's time complexity must be better than O(n log n),
discover the regularities. where n is the array's size.

------------------------------
Credits:Special thanks to @jianchao.li.fighter for adding this ------------------------------
problem and creating all test cases. ------------------------------
------------------------------ Intersection of Two Arrays
------------------------------ ------------------------------
Reverse String
------------------------------ Given two arrays, write a function to compute their intersection.
Write a function that takes a string as input and returns the string
reversed.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Example:
Given s = "hello", return "olleh".
Note:
------------------------------
------------------------------ Each element in the result must be unique.
Reverse Vowels of a String The result can be in any order.
------------------------------
Write a function that takes a string as input and reverse only the
vowels of a string. ------------------------------
------------------------------
Intersection of Two Arrays II
Example 1: ------------------------------
Given s = "hello", return "holle".
Given two arrays, write a function to compute their intersection.

Example 2: Example:
Given s = "leetcode", return "leotcede". Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:
Note:
The vowels does not include the letter "y". Each element in the result should appear as many times as it shows
in both arrays.
------------------------------ The result can be in any order.
------------------------------
------------------------------
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of
Follow up: envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

What if the given array is already sorted? How would you optimize ------------------------------
your algorithm? ------------------------------
What if nums1's size is small compared to nums2's size? Which Design Twitter
algorithm is better? ------------------------------
What if elements of nums2 are stored on disk, and the memory is Design a simplified version of Twitter where users can post tweets,
limited such that you cannot load all elements into the memory at follow/unfollow another user and is able to see the 10 most recent
once? tweets in the user's news feed. Your design should support the
following methods:

------------------------------
------------------------------
------------------------------ postTweet(userId, tweetId): Compose a new tweet.
Data Stream as Disjoint Intervals getNewsFeed(userId): Retrieve the 10 most recent tweet ids in the
------------------------------ user's news feed. Each item in the news feed must be posted by users
Given a data stream input of non-negative integers a1, a2, ..., who the user followed or by the user herself. Tweets must be ordered
an, ..., summarize the numbers seen so far as a list of disjoint from most recent to least recent.
intervals. follow(followerId, followeeId): Follower follows a followee.
unfollow(followerId, followeeId): Follower unfollows a followee.
For example, suppose the integers from the data stream are 1, 3, 7,
2, 6, ..., then the summary will be:

[1, 1] Example:
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7] Twitter twitter = new Twitter();
[1, 3], [7, 7]
[1, 3], [6, 7] // User 1 posts a new tweet (id = 5).
twitter.postTweet(1, 5);

Follow up: // User 1's news feed should return a list with 1 tweet id -> [5].
What if there are lots of merges and the number of disjoint twitter.getNewsFeed(1);
intervals are small compared to the data stream's size?
// User 1 follows user 2.
twitter.follow(1, 2);
Credits:Special thanks to @yunhong for adding this problem and
creating most of the test cases. // User 2 posts a new tweet (id = 6).
------------------------------ twitter.postTweet(2, 6);
------------------------------
------------------------------ // User 1's news feed should return a list with 2 tweet ids -> [6,
Russian Doll Envelopes 5].
------------------------------ // Tweet id 6 should precede tweet id 5 because it is posted after
You have a number of envelopes with widths and heights given as a tweet id 5.
pair of integers (w, h). One envelope can fit into another if and twitter.getNewsFeed(1);
only if both the width and height of one envelope is greater than
the width and height of the other envelope. // User 1 unfollows user 2.
twitter.unfollow(1, 2);

What is the maximum number of envelopes can you Russian doll? (put // User 1's news feed should return a list with 1 tweet id -> [5],
one inside other) // since user 1 is no longer following user 2.
twitter.getNewsFeed(1);

Example:

------------------------------ Pour water from one jug into another till the other jug is
------------------------------ completely full or the first jug itself is empty.
------------------------------
------------------------------
------------------------------
------------------------------ Example 1: (From the famous "Die Hard" example)
------------------------------
------------------------------ Input: x = 3, y = 5, z = 4
Max Sum of Rectangle No Larger Than K Output: True
------------------------------
Given a non-empty 2D matrix matrix and an integer k, find the max
sum of a rectangle in the matrix such that its sum is no larger than
k. Example 2:

Example: Input: x = 2, y = 6, z = 5
Given matrix = [ Output: False
[1, 0, 1],
[0, -2, 3]
]
k = 2 Credits:Special thanks to @vinod23 for adding this problem and
creating all test cases.
------------------------------
------------------------------
The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 ------------------------------
and 2 is the max number no larger than k (k = 2). Valid Perfect Square
------------------------------
Note: Given a positive integer num, write a function which returns True if
num is a perfect square else False.
The rectangle inside the matrix must have an area > 0.
What if the number of rows is much larger than the number of
columns? Note: Do not use any built-in library function such as sqrt.

Example 1:
Credits:Special thanks to @fujiaozhu for adding this problem and
creating all test cases. Input: 16
------------------------------ Returns: True
------------------------------
------------------------------
Water and Jug Problem
------------------------------ Example 2:
You are given two jugs with capacities x and y litres. There is an
infinite amount of water supply available. Input: 14
You need to determine whether it is possible to measure exactly z Returns: False
litres using these two jugs.

If z liters of water is measurable, you must have z liters of water


contained within one or both buckets by the end. Credits:Special thanks to @elmirap for adding this problem and
creating all test cases.
------------------------------
Operations allowed: ------------------------------
Largest Divisible Subset
Fill any of the jugs completely with water. ------------------------------
Empty any of the jugs.
Given a set of distinct positive integers, find the largest subset b = [3]
such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0. Result: 8

If there are multiple solutions, return any subset is fine.


Example2:

Example 1: a = 2
b = [1,0]
nums: [1,2,3]
Result: 1024
Result: [1,2] (of course, [1,3] will also be ok)

Credits:Special thanks to @Stomach_ache for adding this problem and


Example 2: creating all test cases.
------------------------------
nums: [1,2,4,8] ------------------------------
Find K Pairs with Smallest Sums
Result: [1,2,4,8] ------------------------------

You are given two integer arrays nums1 and nums2 sorted in ascending
order and an integer k.
Credits:Special thanks to @Stomach_ache for adding this problem and
creating all test cases.
------------------------------ Define a pair (u,v) which consists of one element from the first
------------------------------ array and one element from the second array.
------------------------------
------------------------------ Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
Sum of Two Integers
------------------------------
Calculate the sum of two integers a and b, but you are not allowed Example 1:
to use the operator + and -.
Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3
Example:
Given a = 1 and b = 2, return 3. Return: [1,2],[1,4],[1,6]

The first 3 pairs are returned from the sequence:


Credits:Special thanks to @fujiaozhu for adding this problem and [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
creating all test cases.
------------------------------
------------------------------
Super Pow Example 2:
------------------------------
Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2
Your task is to calculate ab mod 1337 where a is a positive integer
and b is an extremely large positive integer given in the form of an Return: [1,1],[1,1]
array.
The first 2 pairs are returned from the sequence:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
Example1:

a = 2

Example 3:

Given nums1 = [1,2], nums2 = [3], k = 3 Example:

Return: [1,3],[2,3] n = 10, I pick 8.

All possible pairs are returned from the sequence: First round: You guess 5, I tell you that it's higher. You pay $5.
[1,3],[2,3] Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round: You guess 9, I tell you that it's lower. You pay $9.

Game over. 8 is the number I picked.


Credits:Special thanks to @elmirap and @StefanPochmann for adding
this problem and creating all test cases. You end up paying $5 + $7 + $9 = $21.
------------------------------
------------------------------
Guess Number Higher or Lower
------------------------------ Given a particular n &ge; 1, find out how much money you need to
We are playing the Guess Game. The game is as follows: have to guarantee a win.

I pick a number from 1 to n. You have to guess which number I


picked. The best strategy to play the game is to minimize the maximum
loss you could possibly face. Another strategy is to minimize the
Every time you guess wrong, I'll tell you whether the number is expected loss. Here, we are interested in the first scenario.
higher or lower. Take a small example (n = 3). What do you end up paying in the
worst case?
You call a pre-defined API guess(int num) which returns 3 possible Check out this article if you're still stuck.
results (-1, 1, or 0): The purely recursive implementation of minimax would be worthless
for even a small n. You MUST use dynamic programming.
-1 : My number is lower As a follow-up, how would you modify your code to solve the problem
1 : My number is higher of minimizing the expected loss, instead of the worst-case loss?
0 : Congrats! You got it!

Credits:Special thanks to @agave and @StefanPochmann for adding this


Example: problem and creating all test cases.
------------------------------
n = 10, I pick 6. ------------------------------
Wiggle Subsequence
Return 6. ------------------------------
A sequence of numbers is called a wiggle sequence if the differences
between successive numbers strictly alternate between positive and
------------------------------ negative. The first difference (if one exists) may be either
------------------------------ positive or negative. A sequence with fewer than two elements is
Guess Number Higher or Lower II trivially a wiggle sequence.
------------------------------
We are playing the Guess Game. The game is as follows: For example, [1,7,4,9,2,5] is a wiggle sequence because the
differences (6,-3,5,-7,3) are alternately positive and negative. In
I pick a number from 1 to n. You have to guess which number I contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the
picked. first because its first two differences are positive and the second
because its last difference is zero.
Every time you guess wrong, I'll tell you whether the number I
picked is higher or lower. Given a sequence of integers, return the length of the longest
subsequence that is a wiggle sequence. A subsequence is obtained by
However, when you guess a particular number x, and you guess wrong, deleting some number of elements (eventually, also zero) from the
you pay $x. You win the game when you guess the number I picked. original sequence, leaving the remaining elements in their original
order. How does it change the problem?
What limitation we need to add to the question to allow negative
Examples: numbers?

Input: [1,7,4,9,2,5] Credits:Special thanks to @pbrother for adding this problem and
Output: 6 creating all test cases.
The entire sequence is a wiggle sequence. ------------------------------
------------------------------
Input: [1,17,5,10,13,15,10,5,16,8] Kth Smallest Element in a Sorted Matrix
Output: 7 ------------------------------
There are several subsequences that achieve this length. One is Given a n x n matrix where each of the rows and columns are sorted
[1,17,10,13,10,16,8]. in ascending order, find the kth smallest element in the matrix.

Input: [1,2,3,4,5,6,7,8,9]
Output: 2 Note that it is the kth smallest element in the sorted order, not
the kth distinct element.

Follow up: Example:


Can you do it in O(n) time?
matrix = [
[ 1, 5, 9],
Credits:Special thanks to @agave and @StefanPochmann for adding this [10, 11, 13],
problem and creating all test cases. [12, 13, 15]
------------------------------ ],
------------------------------ k = 8,
Combination Sum IV
------------------------------ return 13.
Given an integer array with all positive numbers and no duplicates,
find the number of possible combinations that add up to a positive
integer target.
Note:
Example: You may assume k is always valid, 1 ≤ k ≤ n2.
------------------------------
nums = [1, 2, 3] ------------------------------
target = 4 ------------------------------
Insert Delete GetRandom O(1)
The possible combination ways are: ------------------------------
(1, 1, 1, 1) Design a data structure that supports all following operations in
(1, 1, 2) average O(1) time.
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2) insert(val): Inserts an item val to the set if not already present.
(3, 1) remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements.
Note that different sequences are counted as different combinations. Each element must have the same probability of being returned.

Therefore the output is 7.

Example:

Follow up: // Init an empty set.


What if negative numbers are allowed in the given array? RandomizedSet randomSet = new RandomizedSet();

// Inserts 2 to the collection, returns true. Collection now


// Inserts 1 to the set. Returns true as 1 was inserted contains [1,1,2].
successfully. collection.insert(2);
randomSet.insert(1);
// getRandom should return 1 with the probability 2/3, and returns 2
// Returns false as 2 does not exist in the set. with the probability 1/3.
randomSet.remove(2); collection.getRandom();

// Inserts 2 to the set, returns true. Set now contains [1,2]. // Removes 1 from the collection, returns true. Collection now
randomSet.insert(2); contains [1,2].
collection.remove(1);
// getRandom should return either 1 or 2 randomly.
randomSet.getRandom(); // getRandom should return 1 and 2 both equally likely.
collection.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
------------------------------
// 2 was already in the set, so return false. ------------------------------
randomSet.insert(2); Linked List Random Node
------------------------------
// Since 2 is the only number in the set, getRandom always return 2. Given a singly linked list, return a random node's value from the
randomSet.getRandom(); linked list. Each node must have the same probability of being
chosen.

------------------------------ Follow up:


------------------------------ What if the linked list is extremely large and its length is unknown
Insert Delete GetRandom O(1) - Duplicates allowed to you? Could you solve this efficiently without using extra space?
------------------------------
Design a data structure that supports all following operations in
average O(1) time. Example:
Note: Duplicate elements are allowed.
// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
insert(val): Inserts an item val to the collection. head.next = new ListNode(2);
remove(val): Removes an item val from the collection if present. head.next.next = new ListNode(3);
getRandom: Returns a random element from current collection of Solution solution = new Solution(head);
elements. The probability of each element being returned is linearly
related to the number of same value the collection contains. // getRandom() should return either 1, 2, or 3 randomly. Each
element should have equal probability of returning.
solution.getRandom();

Example:
------------------------------
// Init an empty collection. ------------------------------
RandomizedCollection collection = new RandomizedCollection(); Ransom Note
------------------------------
// Inserts 1 to the collection. Returns true as the collection did
not contain 1. Given an arbitrary ransom note string and another string containing
collection.insert(1); letters from all the magazines, write a function that will return
true if the ransom
// Inserts another 1 to the collection. Returns false as the note can be constructed from the magazines ; otherwise, it will
collection contained 1. Collection now contains [1,1]. return false.
collection.insert(1);
Each letter in the magazine string can only be used once in your
ransom note.

Example 1:
Note:
You may assume that both strings contain only lowercase letters. Given s = "324",

You should return a NestedInteger object which contains a single


integer 324.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
Example 2:

------------------------------ Given s = "[123,[456,[789]]]",


------------------------------
Shuffle an Array Return a NestedInteger object containing a nested list with 2
------------------------------ elements:
Shuffle a set of numbers without duplicates.
1. An integer containing value 123.
2. A nested list containing two elements:
Example: i. An integer containing value 456.
ii. A nested list with one element:
// Init an array with set 1, 2, and 3. a. An integer containing value 789.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
------------------------------
// Shuffle the array [1,2,3] and return its result. Any permutation ------------------------------
of [1,2,3] must equally likely to be returned. Lexicographical Numbers
solution.shuffle(); ------------------------------

// Resets the array back to its original configuration [1,2,3]. Given an integer n, return 1 - n in lexicographical order.
solution.reset();

// Returns the random shuffling of array [1,2,3].


solution.shuffle(); For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

------------------------------
------------------------------ Please optimize your algorithm to use less time and space. The input
Mini Parser size may be as large as 5,000,000.
------------------------------
Given a nested list of integers represented as a string, implement a ------------------------------
parser to deserialize it. ------------------------------
First Unique Character in a String
Each element is either an integer, or a list -- whose elements may ------------------------------
also be integers or other lists.
Given a string, find the first non-repeating character in it and
Note: return it's index. If it doesn't exist, return -1.
You may assume that the string is well-formed:
Examples:
String is non-empty.
String does not contain white spaces. s = "leetcode"
String contains only digits 0-9, [, - ,, ]. return 0.

s = "loveleetcode", Note:
return 2.
The name of a file contains at least a . and an extension.
The name of a directory or sub-directory will not contain a ..

Note: You may assume the string contain only lowercase letters.
Time complexity required: O(n) where n is the size of the input
------------------------------ string.
------------------------------
Longest Absolute File Path Notice that a/aa/aaa/file1.txt is not the longest file path, if
------------------------------ there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
Suppose we abstract our file system by a string in the following ------------------------------
manner: ------------------------------
Find the Difference
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: ------------------------------

dir Given two strings s and t which consist of only lowercase letters.
subdir1
subdir2 String t is generated by random shuffling string s and then add one
file.ext more letter at a random position.

Find the letter that was added in t.


The directory dir contains an empty sub-directory subdir1 and a sub-
directory subdir2 containing a file file.ext. Example:

The string Input:


"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsu s = "abcd"
bdir2\n\t\t\tfile2.ext" represents: t = "abcde"

dir Output:
subdir1 e
file1.ext
subsubdir1 Explanation:
subdir2 'e' is the letter that was added.
subsubdir2
file2.ext ------------------------------
------------------------------
Elimination Game
The directory dir contains two sub-directories subdir1 and subdir2. ------------------------------
subdir1 contains a file file1.ext and an empty second-level sub-
directory subsubdir1. subdir2 contains a second-level sub-directory There is a list of sorted integers from 1 to n. Starting from left
subsubdir2 containing a file file2.ext. to right, remove the first number and every other number afterward
until you reach the end of the list.
We are interested in finding the longest (number of characters)
absolute path to a file within our file system. For example, in the Repeat the previous step again, but this time from right to left,
second example above, the longest absolute path is "dir/subdir2/ remove the right most number and every other number from the
subsubdir2/file2.ext", and its length is 32 (not including the remaining numbers.
double quotes).
We keep repeating the steps again, alternating left to right and
Given a string representing the file system in the above format, right to left, until a single number remains.
return the length of the longest absolute path to file in the
abstracted file system. If there is no file in the system, return 0. Find the last number that remains starting with a list of length n.
[3,1,4,2],
Example: [3,2,4,4]
]
Input:
n = 9, Return false. Because there is a gap between the two rectangular
1 2 3 4 5 6 7 8 9 regions.
2 4 6 8
2 6
6

Output:
6
Example 3:

------------------------------ rectangles = [
------------------------------ [1,1,3,3],
Perfect Rectangle [3,1,4,2],
------------------------------ [1,3,2,4],
[3,2,4,4]
Given N axis-aligned rectangles where N > 0, determine if they all ]
together form an exact cover of a rectangular region.
Return false. Because there is a gap in the top center.

Each rectangle is represented as a bottom-left point and a top-right


point. For example, a unit square is represented as [1,1,2,2].
(coordinate of bottom-left point is (1, 1) and top-right point is
(2, 2)).
Example 4:

rectangles = [
Example 1: [1,1,3,3],
[3,1,4,2],
rectangles = [ [1,3,2,4],
[1,1,3,3], [2,2,4,4]
[3,1,4,2], ]
[3,2,4,4],
[1,3,2,4], Return false. Because two of the rectangles overlap with each other.
[2,3,3,4]
]

Return true. All 5 rectangles together form an exact cover of a


rectangular region. ------------------------------
------------------------------
Is Subsequence
------------------------------

Given a string s and a string t, check if s is subsequence of t.

Example 2:

rectangles = [ You may assume that there is only lower case English letters in both
[1,1,2,3], s and t. t is potentially a very long (length ~= 500,000) string,
[1,3,2,4], and s is a short string (<=100).

Given an array of integers representing the data, return whether it


is a valid utf-8 encoding.
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 Note:
characters. (ie, "ace" is a subsequence of "abcde" while "aec" is The input is an array of integers. Only the least significant 8 bits
not). of each integer is used to store the data. This means each integer
represents only 1 byte of data.

Example 1:
s = "abc", t = "ahbgdc"
Example 1:

Return true. data = [197, 130, 1], which represents the octet sequence: 11000101
10000010 00000001.

Example 2: Return true.


s = "axc", t = "ahbgdc" It is a valid utf-8 encoding for a 2-bytes character followed by a
1-byte character.

Return false.

Follow up: Example 2:


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 data = [235, 140, 4], which represented the octet sequence: 11101011
this scenario, how would you change your code? 10001100 00000100.

Credits:Special thanks to @pbrother for adding this problem and Return false.
creating all test cases. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-
------------------------------ bytes character.
------------------------------ The next byte is a continuation byte which starts with 10 and that's
UTF-8 Validation correct.
------------------------------ But the second continuation byte does not start with 10, so it is
A character in UTF8 can be from 1 to 4 bytes long, subjected to the invalid.
following rules:

For 1-byte character, the first bit is a 0, followed by its unicode ------------------------------
code. ------------------------------
For n-bytes character, the first n-bits are all one's, the n+1 bit Decode String
is 0, followed by n-1 bytes with most significant 2 bits being 10. ------------------------------

This is how the UTF-8 encoding would work: Given an encoded string, return it's decoded string.

Char. number range | UTF-8 octet sequence


(hexadecimal) | (binary) The encoding rule is: k[encoded_string], where the encoded_string
-------------------- inside the square brackets is being repeated exactly k times. Note
+--------------------------------------------- that k is guaranteed to be a positive integer.
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx You may assume that the input string is always valid; No extra white
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 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 Assume Bk to be an array obtained by rotating the array A k
example, there won't be input like 3a or 2[4]. positions clock-wise, we define a "rotation function" F on A as
follow:

Examples:

s = "3[a]2[bc]", return "aaabcbc". F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1].


s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef". Calculate the maximum value of F(0), F(1), ..., F(n-1).

------------------------------ Note:
------------------------------ n is guaranteed to be less than 105.
Longest Substring with At Least K Repeating Characters
------------------------------
Example:
Find the length of the longest substring T of a given string
(consists of lowercase letters only) such that every character in T A = [4, 3, 2, 6]
appears no less than k times.
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
Example 1: F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
Input:
s = "aaabb", k = 3 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.

Output:
3 ------------------------------
------------------------------
The longest substring is "aaa", as 'a' is repeated 3 times. Integer Replacement
------------------------------

Given a positive integer n and you can do operations as follow:


Example 2:

Input:
s = "ababbc", k = 2
If n is even, replace n with n/2.
Output: If n is odd, you can replace n with either n + 1 or n - 1.
5

The longest substring is "ababb", as 'a' is repeated 2 times and 'b'


is repeated 3 times.
What is the minimum number of replacements needed for n to become 1?

------------------------------
------------------------------
Rotate Function
------------------------------ Example 1:

Given an array of integers A and let n to be its length. Input:


8

Output: Evaluate Division


3 ------------------------------

Explanation: Equations are given in the format A / B = k, where A and B are


8 -> 4 -> 2 -> 1 variables represented as strings, and k is a real number (floating
point number). Given some queries, return the answers. If the answer
does not exist, return -1.0.

Example 2: Example:
Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a
Input: = ?, a / e = ?, a / a = ?, x / x = ? . return [6.0, 0.5, -1.0,
7 1.0, -1.0 ].

Output:
4 The input is: vector&lt;pair&lt;string, string&gt;&gt; equations,
vector&lt;double&gt;&amp; values, vector&lt;pair&lt;string,
Explanation: string&gt;&gt; queries , where equations.size() == values.size(),
7 -> 8 -> 4 -> 2 -> 1 and the values are positive. This represents the equations. Return
or vector&lt;double&gt;.
7 -> 6 -> 3 -> 2 -> 1

According to the example above:


------------------------------ equations = [ ["a", "b"], ["b", "c"] ],
------------------------------ values = [2.0, 3.0],
Random Pick Index queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x",
------------------------------ "x"] ].

Given an array of integers with possible duplicates, randomly output


the index of a given target number. You can assume that the given
target number must exist in the array. The input is always valid. You may assume that evaluating the
queries will result in no division by zero and there is no
contradiction.

Note: ------------------------------
The array size can be very large. Solution that uses too much extra ------------------------------
space will not pass the judge. Nth Digit
------------------------------
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5,
Example: 6, 7, 8, 9, 10, 11, ...

int[] nums = new int[] {1,2,3,3,3}; Note:


Solution solution = new Solution(nums); n is positive and will fit within the range of a 32-bit signed
integer (n < 231).
// pick(3) should return either index 2, 3, or 4 randomly. Each
index should have equal probability of returning.
solution.pick(3); Example 1:

// pick(1) should return 0. Since in the array only nums[0] is equal Input:
to 1. 3
solution.pick(1);
Output:
3
------------------------------
------------------------------
The length of num is less than 10002 and will be &ge; k.
Example 2: The given num does not contain any leading zero.

Input:
11

Output: Example 1:
0
Input: num = "1432219", k = 3
Explanation: Output: "1219"
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Explanation: Remove the three digits 4, 3, and 2 to form the new
11, ... is a 0, which is part of the number 10. number 1219 which is the smallest.

------------------------------
------------------------------ Example 2:
Binary Watch
------------------------------ Input: num = "10200", k = 1
A binary watch has 4 LEDs on the top which represent the hours Output: "200"
(0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Explanation: Remove the leading 1 and the number is 200. Note that
Each LED represents a zero or one, with the least significant bit on the output must not contain leading zeroes.
the right.

For example, the above binary watch reads "3:25".


Example 3:
Given a non-negative integer n which represents the number of LEDs
that are currently on, return all possible times the watch could Input: num = "10", k = 2
represent. Output: "0"
Explanation: Remove all the digits from the number and it is left
Example: with nothing which is 0.
Input: n = 1Return: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02",
"0:04", "0:08", "0:16", "0:32"]
------------------------------
------------------------------
Note: Frog Jump
------------------------------
The order of output does not matter. A frog is crossing a river. The river is divided into x units and at
The hour must not contain a leading zero, for example "01:00" is not each unit there may or may not exist a stone. The frog can jump on a
valid, it should be "1:00". stone, but it must not jump into the water.
The minute must be consist of two digits and may contain a leading
zero, for example "10:2" is not valid, it should be "10:02". Given a list of stones' positions (in units) in sorted ascending
order, determine if the frog is able to cross the river by landing
on the last stone. Initially, the frog is on the first stone and
------------------------------ assume the first jump must be 1 unit.
------------------------------
Remove K Digits
------------------------------ If the frog's last jump was k units, then its next jump must be
Given a non-negative integer num represented as a string, remove k either k - 1, k, or k + 1 units. Note that the frog can only jump in
digits from the number so that the new number is the smallest the forward direction.
possible.
Note:

Note: The number of stones is &ge; 2 and is < 1,100.


Each stone's position will be a non-negative integer < 231.

The first stone's position is always 0.


Note:

All letters in hexadecimal (a-f) must be in lowercase.


Example 1: The hexadecimal string must not contain extra leading 0s. If the
number is zero, it is represented by a single zero character '0';
[0,1,3,5,6,8,12,17] otherwise, the first character in the hexadecimal string will not be
the zero character.
There are a total of 8 stones. The given number is guaranteed to fit within the range of a 32-bit
The first stone at the 0th unit, second stone at the 1st unit, signed integer.
third stone at the 3rd unit, and so on... You must not use any method provided by the library which converts/
The last stone at the 17th unit. formats the number to hex directly.

Return true. The frog can jump to the last stone by jumping
1 unit to the 2nd stone, then 2 units to the 3rd stone, then
2 units to the 4th stone, then 3 units to the 6th stone, Example 1:
4 units to the 7th stone, and 5 units to the 8th stone.
Input:
26

Example 2: Output:
"1a"
[0,1,2,3,4,8,9,11]

Return false. There is no way to jump to the last stone as


the gap between the 5th and 6th stone is too large. Example 2:

Input:
------------------------------ -1
------------------------------
Sum of Left Leaves Output:
------------------------------ "ffffffff"
Find the sum of all left leaves in a given binary tree.

Example: ------------------------------
------------------------------
3 Queue Reconstruction by Height
/ \ ------------------------------
9 20 Suppose you have a random list of people standing in a queue. Each
/ \ person is described by a pair of integers (h, k), where h is the
15 7 height of the person and k is the number of people in front of this
person who have a height greater than or equal to h. Write an
There are two left leaves in the binary tree, with values 9 and 15 algorithm to reconstruct the queue.
respectively. Return 24.

Note:
------------------------------ The number of people is less than 1,100.
------------------------------
Convert a Number to Hexadecimal
------------------------------ Example

Given an integer, write an algorithm to convert it to hexadecimal. Input:


For negative integer, two’s complement method is used. [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output: Note:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] Assume the length of given string will not exceed 1,010.

------------------------------ Example:
------------------------------
Trapping Rain Water II Input:
------------------------------ "abccccdd"
Given an m x n matrix of positive integers representing the height
of each unit cell in a 2D elevation map, compute the volume of water Output:
it is able to trap after raining. 7

Explanation:
Note: One longest palindrome that can be built is "dccaccd", whose length
Both m and n are less than 110. The height of each unit cell is is 7.
greater than 0 and is less than 20,000.

------------------------------
Example: ------------------------------
Split Array Largest Sum
Given the following 3x6 height map: ------------------------------
[ Given an array which consists of non-negative integers and an
[1,4,3,1,3,2], integer m, you can split the array into m non-empty continuous
[3,2,1,3,2,4], subarrays. Write an algorithm to minimize the largest sum among
[2,3,3,2,3,1] these m subarrays.
]

Return 4. Note:
If n is the length of array, assume the following constraints are
satisfied:

1 &le; n &le; 1000


1 &le; m &le; min(50, n)
The above image represents the elevation map [[1,4,3,1,3,2],
[3,2,1,3,2,4],[2,3,3,2,3,1]] before the rain.

Examples:

Input:
After the rain, water are trapped between the blocks. The total nums = [7,2,5,10,8]
volume of water trapped is 4. m = 2

------------------------------ Output:
------------------------------ 18
------------------------------
Longest Palindrome Explanation:
------------------------------ There are four ways to split nums into two subarrays.
Given a string which consists of lowercase or uppercase letters, The best way is to split it into [7,2,5] and [10,8],
find the length of the longest palindromes that can be built with where the largest sum among the two subarrays is only 18.
those letters.

This is case sensitive, for example "Aa" is not considered a ------------------------------


palindrome here. ------------------------------
------------------------------

Fizz Buzz particular, this means that P + 1 < Q.


------------------------------
Write a program that outputs the string representation of numbers The function should return the number of arithmetic slices in the
from 1 to n. array A.

But for multiples of three it should output “Fizz” instead of the


number and for the multiples of five output “Buzz”. For numbers Example:
which are multiples of both three and five output “FizzBuzz”.
A = [1, 2, 3, 4]
Example:
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and
n = 15, [1, 2, 3, 4] itself.

Return: ------------------------------
[ ------------------------------
"1", Third Maximum Number
"2", ------------------------------
"Fizz", Given a non-empty array of integers, return the third maximum number
"4", in this array. If it does not exist, return the maximum number. The
"Buzz", time complexity must be in O(n).
"Fizz",
"7", Example 1:
"8",
"Fizz", Input: [3, 2, 1]
"Buzz",
"11", Output: 1
"Fizz",
"13", Explanation: The third maximum is 1.
"14",
"FizzBuzz"
]
Example 2:

------------------------------ Input: [1, 2]


------------------------------
Arithmetic Slices Output: 2
------------------------------
A sequence of number is called arithmetic if it consists of at least Explanation: The third maximum does not exist, so the maximum (2) is
three elements and if the difference between any two consecutive returned instead.
elements is the same.

For example, these are arithmetic sequence:


1, 3, 5, 7, 9 Example 3:
7, 7, 7, 7
3, -1, -5, -9 Input: [2, 2, 3, 1]

The following sequence is not arithmetic. 1, 1, 2, 5, 7 Output: 1

Explanation: Note that the third maximum here means the third
A zero-indexed array A consisting of N numbers is given. A slice of maximum distinct number.
that array is any pair of integers (P, Q) such that 0 <= P < Q < N. Both numbers with value 2 are both considered as second maximum.

A slice (P, Q) of array A is called arithmetic if the sequence:


A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In ------------------------------
------------------------------ Given an m x n matrix of non-negative integers representing the
Add Strings height of each unit cell in a continent, the "Pacific ocean" touches
------------------------------ the left and top edges of the matrix and the "Atlantic ocean"
Given two non-negative integers num1 and num2 represented as string, touches the right and bottom edges.
return the sum of num1 and num2.
Water can only flow in four directions (up, down, left, or right)
Note: from a cell to another one with height equal or lower.

The length of both num1 and num2 is < 5100. Find the list of grid coordinates where water can flow to both the
Both num1 and num2 contains only digits 0-9. Pacific and Atlantic ocean.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the Note:
inputs to integer directly.
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
------------------------------
------------------------------
Partition Equal Subset Sum Example:
------------------------------
Given a non-empty array containing only positive integers, find if Given the following 5x5 matrix:
the array can be partitioned into two subsets such that the sum of
elements in both subsets is equal. Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
Note: ~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
Each of the array element will not exceed 100. ~ (5) 1 1 2 4 *
The array size will not exceed 200. * * * * * Atlantic

Return:

Example 1: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions
with parentheses in above matrix).
Input: [1, 5, 11, 5]

Output: true ------------------------------


------------------------------
Explanation: The array can be partitioned as [1, 5, 5] and [11]. ------------------------------
Battleships in a Board
------------------------------
Given an 2D board, count how many battleships are in it. The
Example 2: battleships are represented with 'X's, empty slots are represented
with '.'s. You may assume the following rules:
Input: [1, 2, 3, 5]

Output: false You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other
Explanation: The array cannot be partitioned into equal sum subsets. words, they can only be made of the shape 1xN (1 row, N columns) or
Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two
------------------------------ battleships - there are no adjacent battleships.
------------------------------
Pacific Atlantic Water Flow
------------------------------ Example:

X..X Explanation: The maximum result is 5 ^ 25 = 28.


...X
...X
------------------------------
In the above board there are 2 battleships. ------------------------------
------------------------------
Invalid Example: Reconstruct Original Digits from English
...X ------------------------------
XXXX Given a non-empty string containing an out-of-order English
...X representation of digits 0-9, output the digits in ascending order.

This is an invalid board that you will not receive - as battleships Note:
will always have a cell separating between them.
Input contains only lowercase English letters.
Follow up:Could you do it in one-pass, using only O(1) extra memory Input is guaranteed to be valid and can be transformed to its
and without modifying the value of the board? original digits. That means invalid inputs such as "abc" or "zerone"
------------------------------ are not permitted.
------------------------------ Input length is less than 50,000.
Strong Password Checker
------------------------------
A password is considered strong if below conditions are all met:
Example 1:

It has at least 6 characters and at most 20 characters. Input: "owoztneoer"


It must contain at least one lowercase letter, at least one
uppercase letter, and at least one digit. Output: "012"
It must NOT contain three repeating characters in a row
("...aaa..." is weak, but "...aa...a..." is strong, assuming other
conditions are met).
Example 2:

Write a function strongPasswordChecker(s), that takes a string s as Input: "fviefuro"


input, and return the MINIMUM change required to make s a strong
password. If s is already strong, return 0. Output: "45"

Insertion, deletion or replace of any one character are all


considered as one change. ------------------------------
------------------------------ ------------------------------
------------------------------ Longest Repeating Character Replacement
Maximum XOR of Two Numbers in an Array ------------------------------
------------------------------ Given a string that consists of only uppercase English letters, you
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 can replace any letter in the string with another letter at most k
&le; ai < 231. times. Find the length of a longest substring containing all
repeating letters you can get after performing the above operations.
Find the maximum result of ai XOR aj, where 0 &le; i, j &lt; n.
Note:
Could you do this in O(n) runtime? Both the string's length and k will not exceed 104.

Example:

Input: [3, 10, 5, 25, 2, 8] Example 1:

Output: 28 Input:
s = "ABAB", k = 2
Output: Please note that the string does not contain any non-printable
4 characters.

Explanation: Example:
Replace the two 'A's with two 'B's or vice versa.
Input: "Hello, my name is John"
Output: 5

Example 2: ------------------------------
------------------------------
Input: Non-overlapping Intervals
s = "AABABBA", k = 1 ------------------------------

Output: Given a collection of intervals, find the minimum number of


4 intervals you need to remove to make the rest of the intervals non-
overlapping.
Explanation:
Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4. 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.
All O`one Data Structure
------------------------------
Implement a data structure supporting the following operations:
Example 1:

Input: [ [1,2], [2,3], [3,4], [1,3] ]


Inc(Key) - Inserts a new key with value 1. Or increments an
existing key by 1. Key is guaranteed to be a non-empty string. Output: 1
Dec(Key) - If Key's value is 1, remove it from the data structure.
Otherwise decrements an existing key by 1. If the key does not Explanation: [1,3] can be removed and the rest of intervals are non-
exist, this function does nothing. Key is guaranteed to be a non- overlapping.
empty string.
GetMaxKey() - Returns one of the keys with maximal value. If no
element exists, return an empty string "".
GetMinKey() - Returns one of the keys with minimal value. If no Example 2:
element exists, return an empty string "".
Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Challenge: Perform all these in O(1) time complexity. Explanation: You need to remove two [1,2] to make the rest of
intervals non-overlapping.
------------------------------
------------------------------
Number of Segments in a String
------------------------------ Example 3:
Count the number of segments in a string, where a segment is defined
to be a contiguous sequence of non-space characters. Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since Example 3:
they're already non-overlapping.
Input: [ [1,4], [2,3], [3,4] ]

------------------------------ Output: [-1, 2, -1]


------------------------------
Find Right Interval Explanation: There is no satisfied "right" interval for [1,4] and
------------------------------ [3,4].
For [2,3], the interval [3,4] has minimum-"right" start point.
Given a set of intervals, for each of the interval i, check if there
exists an interval j whose start point is bigger than or equal to
the end point of the interval i, which can be called that j is on ------------------------------
the "right" of i. ------------------------------
Path Sum III
------------------------------
You are given a binary tree in which each node contains an integer
For any interval i, you need to store the minimum interval j's value.
index, which means that the interval j has the minimum start point
to build the "right" relationship for interval i. If the interval j Find the number of paths that sum to a given value.
doesn't exist, store -1 for the interval i. Finally, you need output
the stored value of each interval as an array. 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).
Note:
The tree has no more than 1,000 nodes and the values are in the
You may assume the interval's end point is always bigger than its range -1,000,000 to 1,000,000.
start point.
You may assume none of these intervals have the same start point. Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

Example 1: 10
/ \
Input: [ [1,2] ] 5 -3
/ \ \
Output: [-1] 3 2 11
/ \ \
Explanation: There is only one interval in the collection, so it 3 -2 1
outputs -1.
Return 3. The paths that sum to 8 are:

1. 5 -> 3
Example 2: 2. 5 -> 2 -> 1
3. -3 -> 11
Input: [ [3,4], [2,3], [1,2] ]

Output: [-1, 0, 1] ------------------------------


------------------------------
Explanation: There is no satisfied "right" interval for [3,4]. Find All Anagrams in a String
For [2,3], the interval [3,4] has minimum-"right" start point; ------------------------------
For [1,2], the interval [2,3] has minimum-"right" start point. Given a string s and a non-empty string p, find all the start
indices of p's anagrams in s.
Output:
Strings consists of lowercase English letters only and the length of 10
both strings s and p will not be larger than 20,100.
Explanation:
The order of output does not matter. The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7,
8, 9], so the second smallest number is 10.
Example 1:

Input: ------------------------------
s: "cbaebabacd" p: "abc" ------------------------------
Arranging Coins
Output: ------------------------------
[0, 6] You have a total of n coins that you want to form in a staircase
shape, where every k-th row must have exactly k coins.
Explanation:
The substring with start index = 0 is "cba", which is an anagram of Given n, find the total number of full staircase rows that can be
"abc". formed.
The substring with start index = 6 is "bac", which is an anagram of
"abc". n is a non-negative integer and fits within the range of a 32-bit
signed integer.

Example 1:
Example 2:
n = 5
Input:
s: "abab" p: "ab" The coins can form the following rows:
¤
Output: ¤ ¤
[0, 1, 2] ¤ ¤

Explanation: Because the 3rd row is incomplete, we return 2.


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". Example 2:
The substring with start index = 2 is "ab", which is an anagram of
"ab". n = 8

The coins can form the following rows:


------------------------------ ¤
------------------------------ ¤ ¤
------------------------------ ¤ ¤ ¤
K-th Smallest in Lexicographical Order ¤ ¤
------------------------------
Given integers n and k, find the lexicographically k-th smallest Because the 4th row is incomplete, we return 3.
integer in the range from 1 to n.

Note: 1 &le; k &le; n &le; 109. ------------------------------


------------------------------
Example: Find All Duplicates in an Array
------------------------------
Input: Given an array of integers, 1 &le; a[i] &le; n (n = size of array),
n: 13 k: 2 some elements appear twice and others appear once.

A zero-indexed array A consisting of N numbers is given. A


Find all the elements that appear twice in this array. subsequence slice of that array is any sequence of integers (P0,
P1, ..., Pk) such that 0 &le; P0 < P1 < ... < Pk < N.
Could you do it without extra space and in O(n) runtime?
A subsequence slice (P0, P1, ..., Pk) of array A is called
Example: arithmetic if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is
arithmetic. In particular, this means that k &ge; 2.
Input:
[4,3,2,7,8,2,3,1] The function should return the number of arithmetic subsequence
slices in the array A.
Output:
[2,3] The input contains N integers. Every integer is in the range of -231
and 231-1 and 0 &le; N &le; 1000. The output is guaranteed to be
------------------------------ less than 231-1.
------------------------------
------------------------------
Add Two Numbers II Example:
------------------------------
You are given two non-empty linked lists representing two non- Input: [2, 4, 6, 8, 10]
negative integers. The most significant digit comes first and each
of their nodes contain a single digit. Add the two numbers and Output: 7
return it as a linked list.
Explanation:
You may assume the two numbers do not contain any leading zero, All arithmetic subsequence slices are:
except the number 0 itself. [2,4,6]
[4,6,8]
Follow up: [6,8,10]
What if you cannot modify the input lists? In other words, reversing [2,4,6,8]
the lists is not allowed. [4,6,8,10]
[2,4,6,8,10]
[2,6,10]

Example:
------------------------------
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) ------------------------------
Output: 7 -> 8 -> 0 -> 7 Number of Boomerangs
------------------------------
Given n points in the plane that are all pairwise distinct, a
------------------------------ "boomerang" is a tuple of points (i, j, k) such that the distance
------------------------------ between i and j equals the distance between i and k (the order of
Arithmetic Slices II - Subsequence the tuple matters).
------------------------------
A sequence of numbers is called arithmetic if it consists of at Find the number of boomerangs. You may assume that n will be at most
least three elements and if the difference between any two 500 and coordinates of points are all in the range [-10000, 10000]
consecutive elements is the same. (inclusive).

For example, these are arithmetic sequences: Example:


1, 3, 5, 7, 9
7, 7, 7, 7 Input:
3, -1, -5, -9 [[0,0],[1,0],[2,0]]

The following sequence is not arithmetic. 1, 1, 2, 5, 7 Output:


2
Explanation: Given a root node reference of a BST and a key, delete the node with
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]] the given key in the BST. Return the root node reference (possibly
updated) of the BST.

------------------------------ Basically, the deletion can be divided into two stages:


------------------------------
Find All Numbers Disappeared in an Array Search for a node to remove.
------------------------------ If the node is found, delete the node.
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 Note: Time complexity should be O(height of tree).
array.
Example:
Could you do it without extra space and in O(n) runtime? You may
assume the returned list does not count as extra space. root = [5,3,6,2,4,null,7]
key = 3
Example:
5
Input: / \
[4,3,2,7,8,2,3,1] 3 6
/ \ \
Output: 2 4 7
[5,6]
Given key to delete is 3. So we find the node with value 3 and
delete it.
------------------------------
------------------------------ One valid answer is [5,4,6,2,null,null,7], shown in the following
Serialize and Deserialize BST BST.
------------------------------
Serialization is the process of converting a data structure or 5
object into a sequence of bits so that it can be stored in a file or / \
memory buffer, or transmitted across a network connection link to be 4 6
reconstructed later in the same or another computer environment. / \
2 7
Design an algorithm to serialize and deserialize a binary search
tree. There is no restriction on how your serialization/ Another valid answer is [5,2,6,null,4,null,7].
deserialization algorithm should work. You just need to ensure that
a binary search tree can be serialized to a string and this string 5
can be deserialized to the original tree structure. / \
2 6
\ \
The encoded string should be as compact as possible. 4 7

------------------------------
Note: Do not use class member/global/static variables to store ------------------------------
states. Your serialize and deserialize algorithms should be Sort Characters By Frequency
stateless. ------------------------------
Given a string, sort it in decreasing order based on the frequency
------------------------------ of characters.
------------------------------
Delete Node in a BST Example 1:
------------------------------

Input:
"tree" Output:
3
Output:
"eert" Explanation:
Only three moves are needed (remember each move increments two
Explanation: elements):
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
a valid answer.

------------------------------
------------------------------
Example 2: 4Sum II
------------------------------
Input: Given four lists A, B, C, D of integer values, compute how many
"cccaaa" tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is
zero.
Output:
"cccaaa" To make problem a bit easier, all A, B, C, D have same length of N
where 0 &le; N &le; 500. All integers are in the range of -228 to
Explanation: 228 - 1 and the result is guaranteed to be at most 231 - 1.
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid
answer. Example:
Note that "cacaca" is incorrect, as the same characters must be
together. Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
Example 3: D = [ 0, 2]

Input: Output:
"Aabb" 2

Output: Explanation:
"bbAa" The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 =
Explanation: 0
"bbaA" is also a valid answer, but "Aabb" is incorrect. 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 =
Note that 'A' and 'a' are treated as two different characters. 0

------------------------------ ------------------------------
------------------------------ ------------------------------
Minimum Moves to Equal Array Elements Assign Cookies
------------------------------ ------------------------------
Given a non-empty integer array of size n, find the minimum number
of moves required to make all array elements equal, where a move is Assume you are an awesome parent and want to give your children some
incrementing n - 1 elements by 1. cookies. But, you should give each child at most one cookie. Each
child i has a greed factor gi, which is the minimum size of a cookie
Example: that the child will be content with; and each cookie j has a size
sj. If sj >= gi, we can assign the cookie j to the child i, and the
Input: child i will be content. Your goal is to maximize the number of your
[1,2,3] content children and output the maximum number.
Note:
You may assume the greed factor is always positive. Example 2:
You cannot assign more than one cookie to one child.
Input: [3, 1, 4, 2]

Example 1: Output: True

Input: [1,2,3], [1,1] Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of Example 3:
3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you Input: [-1, 3, 2, 0]
could only make the child whose greed factor is 1 content.
You need to output 1. Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3,


2], [-1, 3, 0] and [-1, 2, 0].
Example 2:

Input: [1,2], [1,2,3] ------------------------------


------------------------------
Output: 2 Repeated Substring Pattern
------------------------------
Explanation: You have 2 children and 3 cookies. The greed factors of Given a non-empty string check if it can be constructed by taking a
2 children are 1, 2. substring of it and appending multiple copies of the substring
You have 3 cookies and their sizes are big enough to gratify all of together. You may assume the given string consists of lowercase
the children, English letters only and its length will not exceed 10000.
You need to output 2.
Example 1:

------------------------------ Input: "abab"


------------------------------
132 Pattern Output: True
------------------------------
Explanation: It's the substring "ab" twice.
Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a
subsequence ai, aj, ak such
that i < j < k and ai < ak < aj. Design an algorithm that takes a
list of n numbers as input and checks whether there is a 132 pattern Example 2:
in the list.
Input: "aba"
Note: n will be less than 15,000.
Output: False
Example 1:

Input: [1, 2, 3, 4]
Example 3:
Output: False
Input: "abcabcabcabc"
Explanation: There is no 132 pattern in the sequence.

Output: True Note:


0 &le; x, y &lt; 231.
Explanation: It's the substring "abc" four times. (And the substring
"abcabc" twice.)
Example:

------------------------------ Input: x = 1, y = 4
------------------------------
LFU Cache Output: 2
------------------------------
Design and implement a data structure for Least Frequently Used Explanation:
(LFU) cache. It should support the following operations: get and 1 (0 0 0 1)
put. 4 (0 1 0 0)
↑ ↑

The above arrows point to positions where the corresponding bits are
get(key) - Get the value (will always be positive) of the key if the different.
key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already
present. When the cache reaches its capacity, it should invalidate ------------------------------
the least frequently used item before inserting a new item. For the ------------------------------
purpose of this problem, when there is a tie (i.e., two or more keys Minimum Moves to Equal Array Elements II
that have the same frequency), the least recently used key would be ------------------------------
evicted. Given a non-empty integer array, find the minimum number of moves
required to make all array elements equal, where a move is
incrementing a selected element by 1 or decrementing a selected
Follow up: element by 1.
Could you do both operations in O(1) time complexity?
You may assume the array's length is at most 10,000.
Example:
Example:
LFUCache cache = new LFUCache( 2 /* capacity */ );
Input:
cache.put(1, 1); [1,2,3]
cache.put(2, 2);
cache.get(1); // returns 1 Output:
cache.put(3, 3); // evicts key 2 2
cache.get(2); // returns -1 (not found)
cache.get(3); // returns 3. Explanation:
cache.put(4, 4); // evicts key 1. Only two moves are needed (remember each move increments or
cache.get(1); // returns -1 (not found) decrements one element):
cache.get(3); // returns 3
cache.get(4); // returns 4 [1,2,3] => [2,2,3] => [2,2,2]

------------------------------ ------------------------------
------------------------------ ------------------------------
Hamming Distance Island Perimeter
------------------------------ ------------------------------
The Hamming distance between two integers is the number of positions You are given a map in form of a two-dimensional integer grid where
at which the corresponding bits are different. 1 represents land and 0 represents water. Grid cells are connected
horizontally/vertically (not diagonally). The grid is completely
Given two integers x and y, calculate the Hamming distance. surrounded by water, and there is exactly one island (i.e., one or
more connected land cells). The island doesn't have "lakes" (water
inside that isn't connected to the water around the island). One The second player will win by choosing 10 and get a total = 11,
cell is a square with side length 1. The grid is rectangular, width which is >= desiredTotal.
and height don't exceed 100. Determine the perimeter of the island. Same with other integers chosen by the first player, the second
player will always win.
Example:

[[0,1,0,0], ------------------------------
[1,1,1,0], ------------------------------
[0,1,0,0], ------------------------------
[1,1,0,0]] Count The Repetitions
------------------------------
Answer: 16 Define S = [s,n] as the string S which consists of n connected
Explanation: The perimeter is the 16 yellow stripes in the image strings s. For example, ["abc", 3] ="abcabcabc".
below: On the other hand, we define that string s1 can be obtained from
string s2 if we can remove some characters from s2 such that it
becomes s1. For example, “abc” can be obtained from “abdbec” based
on our definition, but it can not be obtained from “acbbe”.
------------------------------ You are given two non-empty strings s1 and s2 (each at most 100
------------------------------ characters long) and two integers 0 &le; n1 &le; 106 and 1 &le; n2
Can I Win &le; 106. Now consider the strings S1 and S2, where S1=[s1,n1] and
------------------------------ S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be
In the "100 game," two players take turns adding, to a running obtained from S1.
total, any integer from 1..10. The player who first causes the
running total to reach or exceed 100 wins. Example:

What if we change the game so that players cannot re-use integers? Input:
s1="acb", n1=4
For example, two players might take turns drawing from a common pool s2="ab", n2=2
of numbers of 1..15 without replacement until they reach a total >=
100. Return:
2
Given an integer maxChoosableInteger and another integer
desiredTotal, determine if the first player to move can force a win,
assuming both players play optimally. ------------------------------
------------------------------
You can always assume that maxChoosableInteger will not be larger Unique Substrings in Wraparound String
than 20 and desiredTotal will not be larger than 300. ------------------------------
Consider the string s to be the infinite wraparound string of
"abcdefghijklmnopqrstuvwxyz", so s will look like this:
Example "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".

Input: Now we have another string p. Your job is to find out how many
maxChoosableInteger = 10 unique non-empty substrings of p are present in s. In particular,
desiredTotal = 11 your input is the string p and you need to output the number of
different non-empty substrings of p in the string s.
Output:
false Note: p consists of only lowercase English letters and the size of p
might be over 10000.
Explanation:
No matter which integer the first player choose, the first player Example 1:
will lose.
The first player can choose an integer from 1 up to 10. Input: "a"
If the first player choose 1, the second player can only choose Output: 1
integers from 2 up to 10.

Explanation: Only the substring "a" of string "a" is in the string


s. However, we don't replace a consecutive group of zero value with a
single empty group using two consecutive colons (::) to pursue
simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an
invalid IPv6 address.
Example 2:

Input: "cac"
Output: 2 Besides, extra leading zeros in the IPv6 is also invalid. For
Explanation: There are two substrings "a", "c" of string "cac" in example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is
the string s. invalid.

Example 3: Note:
You may assume there is no extra space or special characters in the
Input: "zab" input string.
Output: 6
Explanation: There are six substrings "z", "a", "b", "za", "ab",
"zab" of string "zab" in the string s. Example 1:

Input: "172.16.254.1"
------------------------------
------------------------------ Output: "IPv4"
Validate IP Address
------------------------------ Explanation: This is a valid IPv4 address, return "IPv4".

Write a function to check whether an input string is a valid IPv4


address or IPv6 address or neither.

Example 2:

IPv4 addresses are canonically represented in dot-decimal notation, Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"


which consists of four decimal numbers, each ranging from 0 to 255,
separated by dots ("."), e.g.,172.16.254.1; Output: "IPv6"

Explanation: This is a valid IPv6 address, return "IPv6".

Besides, leading zeros in the IPv4 is invalid. For example, the


address 172.16.254.01 is invalid.
Example 3:

Input: "256.256.256.256"
IPv6 addresses are represented as eight groups of four hexadecimal
digits, each group representing 16 bits. The groups are separated by Output: "Neither"
colons (":"). For example, the address
2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we Explanation: This is neither a IPv4 address nor a IPv6 address.
could omit some leading zeros among four hexadecimal digits and some
low-case characters in the address to upper-case ones, so
2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit ------------------------------
leading zeros and using upper cases). ------------------------------
------------------------------
------------------------------
Concatenated Words
------------------------------
Given a list of words (without duplicates), please write a program Example 2:
that returns all concatenated words in the given list of words.
A concatenated word is defined as a string that is comprised Input: [3,3,3,3,4]
entirely of at least two shorter words in the given array. Output: false

Example: Explanation: You cannot find a way to form a square with all the
matchsticks.
Input:
["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat
","ratcatdogcat"]
Note:
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
The length sum of the given matchsticks is in the range of 0 to
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and 10^9.
"cats"; "dogcatsdog" can be concatenated by "dog", "cats" and The length of the given matchstick array will not exceed 15.
"dog"; "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and
"cat".
------------------------------
------------------------------
Ones and Zeroes
Note: ------------------------------
In the computer world, use restricted resource you have to generate
The number of elements of the given array will not exceed 10,000 maximum benefit is what we always want to pursue.
The length sum of elements in the given array will not exceed For now, suppose you are a dominator of m 0s and n 1s respectively.
600,000. On the other hand, there is an array with strings consisting of only
All the input string will only include lower case letters. 0s and 1s.
The returned elements order does not matter.

Now your task is to find the maximum number of strings that you can
------------------------------ form with given m 0s and n 1s. Each 0 and 1 can be used at most
------------------------------ once.
Matchsticks to Square
------------------------------
Remember the story of Little Match Girl? By now, you know exactly
what matchsticks the little match girl has, please find out a way Note:
you can make one square by using up all those matchsticks. You
should not break any stick, but you can link them up, and each The given numbers of 0s and 1s will both not exceed 100
matchstick must be used exactly one time. The size of given string array won't exceed 600.

Your input will be several matchsticks the girl has, represented


with their stick length. Your output will either be true or false,
to represent whether you could make one square using all the Example 1:
matchsticks the little match girl has.
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Example 1: Output: 4

Input: [1,1,2,2,2] Explanation: This are totally 4 strings can be formed by the using
Output: true of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”

Explanation: You can form a square with length 2, one side of the
square came two sticks with length 1.
Example 2:

Input: Array = {"10", "0", "1"}, m = 1, n = 1 Number Complement


Output: 2 ------------------------------
Given a positive integer, output its complement number. The
Explanation: You could form "10", but then you'd have nothing left. complement strategy is to flip the bits of its binary
Better form "0" and "1". representation.

Note:
------------------------------
------------------------------ The given integer is guaranteed to fit within the range of a 32-bit
Heaters signed integer.
------------------------------ You could assume no leading zero bit in the integer’s binary
Winter is coming! Your first job during the contest is to design a representation.
standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal


line, find out minimum radius of heaters so that all houses could be Example 1:
covered by those heaters.
Input: 5
So, your input will be the positions of houses and heaters Output: 2
seperately, and your expected output will be the minimum radius Explanation: The binary representation of 5 is 101 (no leading zero
standard of heaters. bits), and its complement is 010. So you need to output 2.

Note:

Numbers of houses and heaters you are given are non-negative and Example 2:
will not exceed 25000.
Positions of houses and heaters you are given are non-negative and Input: 1
will not exceed 10^9. Output: 0
As long as a house is in the heaters' warm radius range, it can be Explanation: The binary representation of 1 is 1 (no leading zero
warmed. bits), and its complement is 0. So you need to output 0.
All the heaters follow your radius standard and the warm radius will
the same.
------------------------------
------------------------------
Total Hamming Distance
Example 1: ------------------------------
The Hamming distance between two integers is the number of positions
Input: [1,2,3],[2] at which the corresponding bits are different.
Output: 1
Explanation: The only heater was placed in the position 2, and if we Now your job is to find the total Hamming distance between all pairs
use the radius 1 standard, then all the houses can be warmed. of the given numbers.

Example:
Example 2:
Input: 4, 14, 2
Input: [1,2,3,4],[1,4]
Output: 1 Output: 6
Explanation: The two heater was placed in the position 1 and 4. We
need to use radius 1 standard, then all the houses can be warmed. Explanation: In binary representation, the 4 is 0100, 14 is 1110,
and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
------------------------------ HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14,
------------------------------ 2) = 2 + 2 + 2 = 6.
The string S is magical because concatenating the number of
contiguous occurrences of characters '1' and '2' generates the
string S itself.
Note:

Elements of the given array are in the range of 0 to 10^9


Length of the array will not exceed 10^4. The first few elements of string S is the following:
S = "1221121221221121122……"

------------------------------
------------------------------
Sliding Window Median If we group the consecutive '1's and '2's in S, it will be:
------------------------------
Median is the middle value in an ordered integer list. If the size
of the list is even, there is no middle value. So the median is the 1 22 11 2 1 22 1 22 11 2 11 22 ......
mean of the two middle value.
Examples:
[2,3,4] , the median is 3 and the occurrences of '1's or '2's in each group are:
[2,3], the median is (2 + 3) / 2 = 2.5

Given an array nums, there is a sliding window of size k which is 1 2 2 1 1 2 1 2 2 1 2 2 ......


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. Your job is to output the median array
for each window in the original array. You can see that the occurrence sequence above is the S itself.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Given an integer N as input, return the number of '1's in the first
N number in the magical string S.
Window position Median
--------------- -----
[1 3 -1] -3 5 3 6 7 1 Note:
1 [3 -1 -3] 5 3 6 7 -1 N will not exceed 100,000.
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6 Example 1:

Input: 6
Therefore, return the median sliding window as [1,-1,-1,3,5,6]. Output: 3
Explanation: The first 6 elements of magical string S is "12211" and
Note: it contains three 1's, so return 3.
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for
non-empty array.
------------------------------ ------------------------------
------------------------------ ------------------------------
Magical String License Key Formatting
------------------------------ ------------------------------
Now you are given a string S, which represents a software license
A magical string S consists of only '1' and '2' and obeys the key which we would like to format. The string S is composed of
following rules: alphanumerical characters and dashes. The dashes split the
alphanumerical characters within the string into groups. (i.e. if
there are M dashes, the string is split into M+1 groups). The dashes

in the given string are possibly misplaced.


Example 1:
We want each group of characters to be of length K (except for
possibly the first group, which could be shorter, but still must Input: "13"
contain at least one character). To satisfy this requirement, we Output: "3"
will reinsert dashes. Additionally, all the lower case letters in Explanation: 13 base 3 is 111.
the string must be converted to upper case.

So, you are given a non-empty string S, representing a license key


to format, and an integer K. And you need to return the license key Example 2:
formatted according to the description above.
Input: "4681"
Output: "8"
Example 1: Explanation: 4681 base 8 is 11111.

Input: S = "2-4A0r7-4k", K = 4

Output: "24A0-R74K" Example 3:

Explanation: The string S has been split into two parts, each part Input: "1000000000000000000"
has 4 characters. Output: "999999999999999999"
Explanation: 1000000000000000000 base 999999999999999999 is 11.

Example 2: Note:

Input: S = "2-4A0r7-4k", K = 3 The range of n is [3, 10^18].


The string representing n is always valid and will not have leading
Output: "24-A0R-74K" zeros.

Explanation: The string S has been split into three parts, each part
has 3 characters except the first part as it could be shorter as ------------------------------
said above. ------------------------------
------------------------------
Max Consecutive Ones
------------------------------
Note: Given a binary array, find the maximum number of consecutive 1s in
this array.
The length of string S will not exceed 12,000, and K is a positive
integer. Example 1:
String S consists only of alphanumerical characters (a-z and/or A-Z
and/or 0-9) and dashes(-). Input: [1,1,0,1,1,1]
String S is non-empty. Output: 3
Explanation: The first two digits or the last three digits are
consecutive 1s.
------------------------------ The maximum number of consecutive 1s is 3.
------------------------------
Smallest Good Base
------------------------------
For an integer n, we call k>=2 a good base of n, if all digits of n Note:
base k are 1.
Now given a string representing n, you should return the smallest The input array will only contain 0 and 1.
good base of n in string format. The length of input array is a positive integer and will not exceed
10,000 Think about Zuma Game. You have a row of balls on the table, colored
red(R), yellow(Y), blue(B), green(G), and white(W). You also have
several balls in your hand.
------------------------------
------------------------------ Each time, you may choose a ball in your hand, and insert it into
Predict the Winner the row (including the leftmost place and rightmost place). Then, if
------------------------------ there is a group of 3 or more balls in the same color touching,
Given an array of scores that are non-negative integers. Player 1 remove these balls. Keep doing this until no more balls can be
picks one of the numbers from either end of the array followed by removed.
the player 2 and then player 1 and so on. Each time a player picks a
number, that number will not be available for the next player. This Find the minimal balls you have to insert to remove all the balls on
continues until all the scores have been chosen. The player with the the table. If you cannot remove all the balls, output -1.
maximum score wins.

Given an array of scores, predict whether player 1 is the winner. Examples:


You can assume each player plays to maximize his score. Input: "WRRBBW", "RB"
Output: -1
Example 1: Explanation: WRRBBW -> WRR[R]BBW -> WBBW -> WBB[B]W -> WW

Input: [1, 5, 2] Input: "WWRRBBWW", "WRBRW"


Output: False Output: 2
Explanation: Initially, player 1 can choose between 1 and 2. If he Explanation: WWRRBBWW -> WWRR[R]BBWW -> WWBBWW -> WWBB[B]WW -> WWWW
chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If -> empty
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, Input:"G", "GGGGG"
player 1 will never be the winner and you need to return False. Output: 2
Explanation: G -> G[G] -> GG[G] -> empty

Input: "RBYYBBRRB", "YRBGB"


Example 2: Output: 3
Explanation: RBYYBBRRB -> RBYY[Y]BBRRB -> RBBBRRB -> RRRB -> B ->
Input: [1, 5, 233, 7] B[B] -> BB[B] -> empty
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose
between 5 and 7. No matter which number player 2 choose, player 1
can choose 233.Finally, player 1 has more score (234) than player 2 Note:
(12), so you need to return True representing player1 can win.
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
Note: represents these balls is called "board" in the input.
The number of balls in your hand won't exceed 5, and the string
1 <= length of the array <= 20. represents these balls is called "hand" in the input.
Any scores in the given array are non-negative integers and will not Both input strings will be non-empty and only contain characters
exceed 10,000,000. 'R','Y','B','G','W'.
If the scores of both players are equal, then player 1 is still the
winner.
------------------------------
------------------------------
------------------------------ ------------------------------
------------------------------ Increasing Subsequences
------------------------------ ------------------------------
Zuma Game
------------------------------ Given an integer array, your task is to find all the different

possible increasing subsequences of the given array, and the length


of an increasing subsequence should be at least 2 . 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.
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]] Reverse Pairs
------------------------------
Given an array nums, we call (i, j) an important reverse pair if i
&lt; j and nums[i] &gt; 2*nums[j].
Note:
You need to return the number of important reverse pairs in the
The length of the given array will not exceed 15. given array.
The range of integer in the given array is [-100,100].
The given array may contain duplicates, and two equal integers Example1:
should also be considered as a special case of increasing sequence.
Input: [1,3,2,3,1]
Output: 2
------------------------------
------------------------------
Construct the Rectangle Example2:
------------------------------
Input: [2,4,3,5,1]
For a web developer, it is very important to know how to design a Output: 3
web page's size. So, given a specific rectangular web page’s area,
your job by now is to design a rectangular web page, whose length L
and width W satisfy the following requirements: Note:
1. The area of the rectangular web page you designed must equal to
the given target area. The length of the given array will not exceed 50,000.
2. The width W should not be larger than the length L, which means L All the numbers in the input array are in the range of 32-bit
>= W. integer.
3. The difference between length L and width W should be as small as
possible.
------------------------------
You need to output the length L and the width W of the web page you ------------------------------
designed in sequence. Target Sum
------------------------------

You are given a list of non-negative integers, a1, a2, ..., an, and
Example: a target, S. Now you have 2 symbols + and -. For each integer, you
should choose one from + and - as its new symbol.
Input: 4
Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to Find out how many ways to assign symbols to make sum of integers
construct it are [1,4], [2,2], [4,1]. equal to target S.
But according to requirement 2, [1,4] is illegal; according to
requirement 3, [4,1] is not optimal compared to [2,2]. So the
length L is 2, and the width W is 2. Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3.


Output: 5
Note: Explanation:
end of time point 2. However, at the beginning of time point 2,
-1+1+1+1+1 = 3 Teemo attacks Ashe again who is already in poisoned status. Since
+1-1+1+1+1 = 3 the poisoned status won't add up together, though the second
+1+1-1+1+1 = 3 poisoning attack will still work at time point 2, it will stop at
+1+1+1-1+1 = 3 the end of time point 3. So you finally need to output 3.
+1+1+1+1-1 = 3

There are 5 ways to assign symbols to make the sum of nums be target
3.
Note:

You may assume the length of given time series array won't exceed
Note: 10000.
You may assume the numbers in the Teemo's attacking time series and
The length of the given array is positive and will not exceed 20. his poisoning time duration per attacking are non-negative integers,
The sum of elements in the given array will not exceed 1000. which won't exceed 10,000,000.
Your output answer is guaranteed to be fitted in a 32-bit integer.

------------------------------
------------------------------ ------------------------------
------------------------------ Next Greater Element I
Teemo Attacking ------------------------------
------------------------------
You are given two arrays (without duplicates) nums1 and nums2 where
In LLP world, there is a hero called Teemo and his attacking can nums1’s elements are subset of nums2. Find all the next greater
make his enemy Ashe be in poisoned condition. Now, given the Teemo's numbers for nums1's elements in the corresponding places of nums2.
attacking ascending time series towards Ashe and the poisoning time
duration per Teemo's attacking, you need to output the total time
that Ashe is in poisoned condition.
The Next Greater Number of a number x in nums1 is the first greater
number to its right in nums2. If it does not exist, output -1 for
You may assume that Teemo attacks at the very beginning of a this number.
specific time point, and makes Ashe be in poisoned condition
immediately.
Example 1:
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Input: [1,4], 2 Output: [-1,3,-1]
Output: 4 Explanation:
Explanation: At time point 1, Teemo starts attacking Ashe and makes For number 4 in the first array, you cannot find the next
Ashe be poisoned immediately. This poisoned status will last 2 greater number for it in the second array, so output -1.
seconds until the end of time point 2. And at time point 4, Teemo For number 1 in the first array, the next greater number for it
attacks Ashe again, and causes Ashe to be in poisoned status for in the second array is 3.
another 2 seconds. So you finally need to output 4. For number 2 in the first array, there is no next greater number
for it in the second array, so output -1.

Example 2: Example 2:

Input: [1,2], 2 Input: nums1 = [2,4], nums2 = [1,2,3,4].


Output: 3 Output: [3,-1]
Explanation: At time point 1, Teemo starts attacking Ashe and makes Explanation:
Ashe be poisoned. This poisoned status will last 2 seconds until the For number 2 in the first array, the next greater number for it

in the second array is 3.


For number 4 in the first array, there is no next greater number
for it in the second array, so output -1.

Example 1:

Input: ["Hello", "Alaska", "Dad", "Peace"]


Note: Output: ["Alaska", "Dad"]

All elements in nums1 and nums2 are unique.


The length of both nums1 and nums2 would not exceed 1000.
Note:

------------------------------ You may use one character in the keyboard more than once.
------------------------------ You may assume the input string will only contain letters of
Diagonal Traverse alphabet.
------------------------------

Given a matrix of M x N elements (M rows, N columns), return all ------------------------------


elements of the matrix in diagonal order as shown in the below ------------------------------
image. Find Mode in Binary Search Tree
------------------------------
Given a binary search tree (BST) with duplicates, find all the
Example: mode(s) (the most frequently occurred element) in the given BST.

Input:
[ Assume a BST is defined as follows:
[ 1, 2, 3 ],
[ 4, 5, 6 ], The left subtree of a node contains only nodes with keys less than
[ 7, 8, 9 ] or equal to the node's key.
] The right subtree of a node contains only nodes with keys greater
Output: [1,2,4,7,5,3,6,8,9] than or equal to the node's key.
Explanation: Both the left and right subtrees must also be binary search trees.

Note: For example:


Given BST [1,null,2,2],
The total number of elements of the given matrix will not exceed
10,000. 1
\
2
------------------------------ /
------------------------------ 2
------------------------------
Keyboard Row
------------------------------
Given a List of words, return the words that can be typed using return [2].
letters of alphabet on only one row's of American keyboard like the
image below.
Note:
If a tree has more than one mode, you can return them in any order.
You may assume all numbers in the input are non-negative integers.
Follow up: The length of Profits array and Capital array will not exceed
Could you do that without using any extra space? (Assume that the 50,000.
implicit stack space incurred due to recursion does not count). The answer is guaranteed to fit in a 32-bit signed integer.

------------------------------
------------------------------ ------------------------------
IPO ------------------------------
------------------------------ Next Greater Element II
------------------------------
Suppose LeetCode will start its IPO soon. In order to sell a good
price of its shares to Venture Capital, LeetCode would like to work Given a circular array (the next element of the last element is the
on some projects to increase its capital before the IPO. Since it first element of the array), print the Next Greater Number for every
has limited resources, it can only finish at most k distinct element. The Next Greater Number of a number x is the first greater
projects before the IPO. Help LeetCode design the best way to number to its traversing-order next in the array, which means you
maximize its total capital after finishing at most k distinct could search circularly to find its next greater number. If it
projects. doesn't exist, output -1 for this number.

Example 1:
You are given several projects. For each project i, it has a pure
profit Pi and a minimum capital of Ci is needed to start the Input: [1,2,1]
corresponding project. Initially, you have W capital. When you Output: [2,-1,2]
finish a project, you will obtain its pure profit and the profit Explanation: The first 1's next greater number is 2; The number 2
will be added to your total capital. can't find next greater number; The second 1's next greater number
needs to search circularly, which is also 2.

To sum up, pick a list of at most k distinct projects from given


projects to maximize your final capital, and output your final Note:
maximized capital. The length of given array won't exceed 10000.

------------------------------
Example 1: ------------------------------
Base 7
Input: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1]. ------------------------------
Given an integer, return its base 7 string representation.
Output: 4
Example 1:
Explanation: Since your initial capital is 0, you can only start the
project indexed 0. Input: 100
After finishing it you will obtain profit 1 and your Output: "202"
capital becomes 1.
With capital 1, you can either start the project
indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to Example 2:
finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is Input: -7
0 + 1 + 3 = 4. Output: "-10"

Note: Note:
The input will be in range of [-1e7, 1e7].

------------------------------ Given the root of a tree, you are asked to find the most frequent
------------------------------ subtree sum. The subtree sum of a node is defined as the sum of all
------------------------------ the node values formed by the subtree rooted at that node (including
Relative Ranks the node itself). So what is the most frequent subtree sum value? If
------------------------------ there is a tie, return all the values with the highest frequency in
any order.
Given scores of N athletes, find their relative ranks and the people
with the top three highest scores, who will be awarded medals: "Gold
Medal", "Silver Medal" and "Bronze Medal". Examples 1
Input:
Example 1:
5
Input: [5, 4, 3, 2, 1] / \
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] 2 -3
Explanation: The first three athletes got the top three highest
scores, so they got "Gold Medal", "Silver Medal" and "Bronze Medal". return [2, -3, 4], since all the values happen only once, return all
For the left two athletes, you just need to output their relative of them in any order.
ranks according to their scores.

Examples 2
Input:
Note:
5
N is a positive integer and won't exceed 10,000. / \
All the scores of athletes are guaranteed to be unique. 2 -5

return [2], since 2 happens twice, however -5 only occur once.


------------------------------
------------------------------
Perfect Number Note:
------------------------------ You may assume the sum of values in any subtree is in the range of
We define the Perfect Number is a positive integer that is equal to 32-bit signed integer.
the sum of all its positive divisors except itself.
------------------------------
Now, given an integer n, write a function that returns true when it ------------------------------
is a perfect number and false when it is not. Find Bottom Left Tree Value
------------------------------

Example: Given a binary tree, find the leftmost value in the last row of the
tree.
Input: 28
Output: True
Explanation: 28 = 1 + 2 + 4 + 7 + 14 Example 1:

Input:

Note: 2
The input number n will not exceed 100,000,000. (1e8) / \
1 3
------------------------------
------------------------------ Output:
Most Frequent Subtree Sum 1
------------------------------
step. After the pressing, you could begin to spell the next
character in the key (next stage), otherwise, you've finished all
Example 2: the spelling.

Input:

1
/ \ Example:
2 3
/ / \
4 5 6
/
7
Input: ring = "godding", key = "gd"
Output: Output: 4
7 Explanation: For the first key character 'g', since it is already in
place, we just need 1 step to spell this character. For the second
key character 'd', we need to rotate the ring "godding"
anticlockwise by two steps to make it become "ddinggo". Also, we
Note: need 1 more step for spelling. So the final output is 4.
You may assume the tree (i.e., the given root node) is not NULL.

------------------------------
------------------------------ Note:
Freedom Trail
------------------------------ Length of both ring and key will be in range 1 to 100.
There are only lowercase letters in both strings and might be some
In the video game Fallout 4, the quest "Road to Freedom" requires duplcate characters in both strings.
players to reach a metal dial called the "Freedom Trail Ring", and It's guaranteed that string key could always be spelled by rotating
use the dial to spell a specific keyword in order to open the door. the string ring.

------------------------------
Given a string ring, which represents the code engraved on the outer ------------------------------
ring and another string key, which represents the keyword needs to Find Largest Value in Each Tree Row
be spelled. You need to find the minimum number of steps in order to ------------------------------
spell all the characters in the keyword. You need to find the largest value in each row of a binary tree.

Initially, the first character of the ring is aligned at 12:00 Example:


direction. You need to spell all the characters in the string key
one by one by rotating the ring clockwise or anticlockwise to make Input:
each character of the string key aligned at 12:00 direction and then
by pressing the center button. 1
/ \
3 2
At the stage of rotating the ring to spell the key character key[i]: / \ \
5 3 9
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 Output: [1, 3, 9]
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 Longest Palindromic Subsequence

------------------------------ 2nd move: 1 <-- 1 <-- 4 => 2 1 3


3rd move: 2 1 <-- 3 => 2 2 2
Given a string s, find the longest palindromic subsequence's length
in s. You may assume that the maximum length of s is 1000.
Example2

Example 1: Input: [0,3,0]


Input:
Output: 2
"bbbab"
Explanation:
Output: 1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
4

One possible longest palindromic subsequence is "bbbb". Example3

Input: [0,2,0]
Example 2:
Input: Output: -1

"cbbd" Explanation:
It's impossible to make all the three washing machines have the same
Output: number of dresses.

One possible longest palindromic subsequence is "bb".


Note:
------------------------------
------------------------------ The range of n is [1, 10000].
Super Washing Machines The range of dresses number in a super washing machine is [0, 1e5].
------------------------------
You have n super washing machines on a line. Initially, each washing
machine has some dresses or is empty. ------------------------------
------------------------------
Detect Capital
For each move, you could choose any m (1 ≤ m ≤ n) washing machines, ------------------------------
and pass one dress of each washing machine to one of its adjacent
washing machines at the same time . Given a word, you need to judge whether the usage of capitals in it
is right or not.
Given an integer array representing the number of dresses in each
washing machine from left to right on the line, you should find the
minimum number of moves to make all the washing machines have the
same number of dresses. If it is not possible to do it, return -1. We define the usage of capitals in a word to be right when one of
the following cases holds:
Example1
All letters in this word are capitals, like "USA".
Input: [1,0,5] All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital if it has more than
Output: 3 one letter, like "Google".

Explanation: Otherwise, we define that this word doesn't use capitals in a right
1st move: 1 0 <-- 5 => 1 1 4 way.
All the given strings' lengths will not exceed 10.
The length of the given list will be in the range of [2, 50].
Example 1:

Input: "USA" ------------------------------


Output: True ------------------------------
Continuous Subarray Sum
------------------------------

Example 2: Given a list of non-negative numbers and a target integer k, write a


function to check if the array has a continuous subarray of size at
Input: "FlaG" least 2 that sums up to the multiple of k, that is, sums up to n*k
Output: False where n is also an integer.

Note: Example 1:
The input will be a non-empty word consisting of uppercase and
lowercase latin letters. Input: [23, 2, 4, 6, 7], k=6
Output: True
------------------------------ Explanation: Because [2, 4] is a continuous subarray of size 2 and
------------------------------ sums up to 6.
------------------------------
Longest Uncommon Subsequence II
------------------------------

Given a list of strings, you need to find the longest uncommon Example 2:
subsequence among them. The longest uncommon subsequence is defined
as the longest subsequence of one of these strings and this Input: [23, 2, 6, 4, 7], k=6
subsequence should not be any subsequence of the other strings. Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of
size 5 and sums up to 42.

A subsequence is a sequence that can be derived from one sequence by


deleting some characters without changing the order of the remaining
elements. Trivially, any string is a subsequence of itself and an Note:
empty string is a subsequence of any string.
The length of the array won't exceed 10,000.
You may assume the sum of all the numbers is in the range of a
signed 32-bit integer.
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. ------------------------------
------------------------------
Longest Word in Dictionary through Deleting
Example 1: ------------------------------

Input: "aba", "cdc", "eae" Given a string and a string dictionary, find the longest string in
Output: 3 the dictionary that can be formed by deleting some characters of the
given string. If there are more than one possible results, return
the longest word with the smallest lexicographical order. If there
is no possible result, return the empty string.
Note:

Example 1: Note:
The length of the given binary array will not exceed 50,000.
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"] ------------------------------
------------------------------
Output: Beautiful Arrangement
"apple" ------------------------------

Suppose you have N integers from 1 to N. We define a beautiful


arrangement as an array that is constructed by these N numbers
successfully if one of the following is true for the ith position (1
Example 2: ≤ i ≤ N) in this array:

Input: The number at the ith position is divisible by i.


s = "abpcplea", d = ["a","b","c"] i is divisible by the number at the ith position.

Output:
"a"

Now given N, how many beautiful arrangements can you construct?

Note:
Example 1:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won't exceed 1,000. Input: 2
The length of all the strings in the input won't exceed 1,000. Output: 2
Explanation:
The first beautiful arrangement is [1, 2]:
------------------------------ Number at the 1st position (i=1) is 1, and 1 is divisible by i
------------------------------ (i=1).
Contiguous Array Number at the 2nd position (i=2) is 2, and 2 is divisible by i
------------------------------ (i=2).
Given a binary array, find the maximum length of a contiguous The second beautiful arrangement is [2, 1]:
subarray with equal number of 0 and 1. Number at the 1st position (i=1) is 2, and 2 is divisible by i
(i=1).
Number at the 2nd position (i=2) is 1, and i (i=2) is divisible by
Example 1: 1.

Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal Note:
number of 0 and 1.
N is a positive integer and will not exceed 15.

Example 2: ------------------------------
------------------------------
Input: [0,1,0] ------------------------------
Output: 2 Minesweeper
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray ------------------------------
with equal number of 0 and 1. Let's play the minesweeper game (Wikipedia, online game)!

You are given a 2D char matrix representing the game board. 'M'
represents an unrevealed mine, 'E' represents an unrevealed empty
square, 'B' represents a revealed blank square that has no adjacent
(above, below, left, right, and all 4 diagonals) mines, digit ('1' Click : [1,2]
to '8') represents how many mines are adjacent to this revealed
square, and finally 'X' represents a revealed mine. Output:

Now given the next click position (row and column indices) among all [['B', '1', 'E', '1', 'B'],
the unrevealed squares ('M' or 'E'), return the board after ['B', '1', 'X', '1', 'B'],
revealing this position according to the following rules: ['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]

Explanation:
If a mine ('M') is revealed, then the game is over - change it to
'X'.
If an empty square ('E') with no adjacent mines is revealed, then
change it to revealed blank ('B') and all of its adjacent unrevealed
squares should be revealed recursively.
If an empty square ('E') with at least one adjacent mine is
revealed, then change it to a digit ('1' to '8') representing the Note:
number of adjacent mines.
Return the board when no more squares will be revealed. The range of the input matrix's height and width is [1,50].
The click position will only be an unrevealed square ('M' or 'E'),
which also means the input board contains at least one clickable
square.
Example 1: The input board won't be a stage when game is over (some mines have
been revealed).
Input: For simplicity, not mentioned rules should be ignored in this
problem. For example, you don't need to reveal all the unrevealed
[['E', 'E', 'E', 'E', 'E'], mines when the game is over, consider any cases that you will win
['E', 'E', 'M', 'E', 'E'], the game or flag any squares.
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
------------------------------
Click : [3,0] ------------------------------
Minimum Absolute Difference in BST
Output: ------------------------------
Given a binary search tree with non-negative values, find the
[['B', '1', 'E', '1', 'B'], minimum absolute difference between values of any two nodes.
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']] Example:

Explanation: Input:

1
\
3
Example 2: /
2
Input:
Output:
[['B', '1', 'E', '1', 'B'], 1
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'], Explanation:
['B', 'B', 'B', 'B', 'B']] The minimum absolute difference is 1, which is the difference

between 2 and 1 (or between 2 and 3).

------------------------------
------------------------------
------------------------------
Note: Encode and Decode TinyURL
There are at least two nodes in this BST. ------------------------------
Note: This is a companion problem to the System Design problem:
------------------------------ Design TinyURL.
------------------------------
------------------------------ TinyURL is a URL shortening service where you enter a URL such as
K-diff Pairs in an Array https://leetcode.com/problems/design-tinyurl and it returns a short
------------------------------ URL such as http://tinyurl.com/4e9iAk.

Given an array of integers and an integer k, you need to find the Design the encode and decode methods for the TinyURL service. There
number of unique k-diff pairs in the array. Here a k-diff pair is is no restriction on how your encode/decode algorithm should work.
defined as an integer pair (i, j), where i and j are both numbers in You just need to ensure that a URL can be encoded to a tiny URL and
the array and their absolute difference is k. the tiny URL can be decoded to the original URL.
------------------------------
------------------------------
------------------------------
Example 1: Complex Number Multiplication
------------------------------
Input: [3, 1, 4, 1, 5], k = 2
Output: 2 Given two strings representing two complex numbers.
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3,
5).Although we have two 1s in the input, we should only return the
number of unique pairs. You need to return a string representing their multiplication. Note
i2 = -1 according to the definition.

Example 2: Example 1:

Input:[1, 2, 3, 4, 5], k = 1 Input: "1+1i", "1+1i"


Output: 4 Output: "0+2i"
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need
3), (3, 4) and (4, 5). convert it to the form of 0+2i.

Example 3: Example 2:

Input: [1, 3, 1, 5, 4], k = 0 Input: "1+-1i", "1+-1i"


Output: 1 Output: "0+-2i"
Explanation: There is one 0-diff pair in the array, (1, 1). Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need
convert it to the form of 0+-2i.

Note:
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000. The input strings will not have extra blank.
All the integers in the given input belong to the range: [-1e7, The input strings will be given in the form of a+bi, where the
1e7]. integer a and b will both belong to the range of [-100, 100]. And
the output should be also in this form. string. If there are less than k characters left, reverse all of
them. If there are less than 2k but greater than or equal to k
characters, then reverse the first k characters and left the other
------------------------------ as original.
------------------------------
Convert BST to Greater Tree
------------------------------ Example:
Given a Binary Search Tree (BST), convert it to a Greater Tree such
that every key of the original BST is changed to the original key Input: s = "abcdefg", k = 2
plus sum of all keys greater than the original key in BST. Output: "bacdfeg"

Example:
Restrictions:
Input: The root of a Binary Search Tree like this:
5 The string consists of lower English letters only.
/ \ Length of the given string and k will in the range [1, 10000]
2 13
------------------------------
Output: The root of a Greater Tree like this: ------------------------------
18 01 Matrix
/ \ ------------------------------
20 13
Given a matrix consists of 0 and 1, find the distance of the nearest
0 for each cell.
------------------------------
------------------------------ The distance between two adjacent cells is 1.
Minimum Time Difference
------------------------------ Example 1:
Given a list of 24-hour clock time points in "Hour:Minutes" format, Input:
find the minimum minutes difference between any two time points in
the list. 0 0 0
0 1 0
Example 1: 0 0 0

Input: ["23:59","00:00"] Output:


Output: 1
0 0 0
0 1 0
0 0 0
Note:

The number of time points in the given list is at least 2 and won't
exceed 20000. Example 2:
The input time is legal and ranges from 00:00 to 23:59. Input:

0 0 0
------------------------------ 0 1 0
------------------------------ 1 1 1
Reverse String II
------------------------------ Output:

Given a string and an integer k, you need to reverse the first k 0 0 0


characters for every 2k characters counting from the start of the 0 1 0

1 2 1 Find the maximum points you can get.

Example 1:
Note: Input:

The number of elements of the given matrix will not exceed 10,000. [1, 3, 2, 2, 2, 3, 4, 3, 1]
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and Output:
right.
23

------------------------------ Explanation:
------------------------------
Diameter of Binary Tree [1, 3, 2, 2, 2, 3, 4, 3, 1]
------------------------------ ----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
----> [1, 3, 3, 3, 1] (1*1=1 points)
Given a binary tree, you need to compute the length of the diameter ----> [1, 1] (3*3=9 points)
of the tree. The diameter of a binary tree is the length of the ----> [] (2*2=4 points)
longest path between any two nodes in a tree. This path may or may
not pass through the root.

Note:
The number of boxes n would not exceed 100.
Example:
Given a binary tree ------------------------------
------------------------------
1 Friend Circles
/ \ ------------------------------
2 3
/ \ There are N students in a class. Some of them are friends, while
4 5 some are not. Their friendship is transitive in nature. For example,
if A is a direct friend of B, and B is a direct friend of C, then A
is an indirect friend of C. And we defined a friend circle is a
group of students who are direct or indirect friends.
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: Given a N*N matrix M representing the friend relationship between


The length of path between two nodes is represented by the number of students in the class. If M[i][j] = 1, then the ith and jth students
edges between them. are direct friends with each other, otherwise not. And you have to
output the total number of friend circles among all the students.
------------------------------
------------------------------
------------------------------ Example 1:
------------------------------
Remove Boxes Input:
------------------------------ [[1,1,0],
Given several boxes with different colors represented by different [1,1,0],
positive numbers. [0,0,1]]
You may experience several rounds to remove boxes until there is no Output: 2
box left. Each time you can choose some continuous boxes with the Explanation:The 0th and 1st students are direct friends, so they are
same color (composed of k boxes, k >= 1), remove them and get k*k in a friend circle. The 2nd student himself is in a friend circle.
points. So return 2.
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
Example 2: correct way to solve a problem). If you have more ideas or
questions, please ask in Discuss and we may compile it here!
Input:
[[1,1,0], Questions:
[1,1,1],
[0,1,1]] How many unique identifiers possible? Will you run out of unique
Output: 1 URLs?
Explanation:The 0th and 1st students are direct friends, the 1st and Should the identifier be increment or not? Which is easier to
2nd students are direct friends, so the 0th and 2nd students are design? Pros and cons?
indirect friends. All of them are in the same friend circle, so Mapping an identifier to an URL and its reversal - Does this problem
return 1. 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.
Note: Estimate the maximum number of queries per second (QPS) for decoding
a shortened URL in a single machine.
N is in range [1,200]. How would you scale the service? For example, a viral link which is
M[i][i] = 1 for all students. shared in social media could result in a peak QPS at a moment's
If M[i][j] = 1, then M[j][i] = 1. 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
Design TinyURL by @alex_svetkin)
------------------------------ If you can enable caching, what would you cache and what's the
Note: For the coding companion problem, please see: Encode and expiry time? (Contributed by @Humandroid)
Decode TinyURL.

How would you design a URL shortening service that is similar to


TinyURL?
.hilight {
Background: color: #d14;
TinyURL is a URL shortening service where you enter a URL such as background-color: #f7f7f9;
https://leetcode.com/problems/design-tinyurl and it returns a short padding: 1px 3px;
URL such as http://tinyurl.com/4e9iAk. border: 1px solid #e1e1e8"
}

Requirements: ------------------------------
------------------------------
For instance, "http://tinyurl.com/4e9iAk" is the tiny url for the License Key Formatting
page "https://leetcode.com/problems/design-tinyurl". The identifier ------------------------------
(the highlighted part) can be any string with 6 alphanumeric Now you are given a string S, which represents a software license
characters containing 0-9, a-z, A-Z. key which we would like to format. The string S is composed of
alphanumerical characters and dashes. The dashes split the
Each shortened URL must be unique; that is, no two different URLs alphanumerical characters within the string into groups. (i.e. if
can be shortened to the same URL. there are M dashes, the string is split into M+1 groups). The dashes
in the given string are possibly misplaced.

We want each group of characters to be of length K (except for

possibly the first group, which could be shorter, but still must subdir2
contain at least one character). To satisfy this requirement, we file.ext
will reinsert dashes. Additionally, all the lower case letters in
the string must be converted to upper case.
The directory dir contains an empty sub-directory subdir1 and a sub-
So, you are given a non-empty string S, representing a license key directory subdir2 containing a file file.ext.
to format, and an integer K. And you need to return the license key
formatted according to the description above. The string
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsu
bdir2\n\t\t\tfile2.ext" represents:
Example 1:
dir
Input: S = "2-4A0r7-4k", K = 4 subdir1
file1.ext
Output: "24A0-R74K" subsubdir1
subdir2
Explanation: The string S has been split into two parts, each part subsubdir2
has 4 characters. file2.ext

The directory dir contains two sub-directories subdir1 and subdir2.


subdir1 contains a file file1.ext and an empty second-level sub-
Example 2: directory subsubdir1. subdir2 contains a second-level sub-directory
subsubdir2 containing a file file2.ext.
Input: S = "2-4A0r7-4k", K = 3
We are interested in finding the longest (number of characters)
Output: "24-A0R-74K" absolute path to a file within our file system. For example, in the
second example above, the longest absolute path is "dir/subdir2/
Explanation: The string S has been split into three parts, each part subsubdir2/file2.ext", and its length is 32 (not including the
has 3 characters except the first part as it could be shorter as double quotes).
said above.
Given a string representing the file system in the above format,
return the length of the longest absolute path to file in the
abstracted file system. If there is no file in the system, return 0.
Note:
Note:
The length of string S will not exceed 12,000, and K is a positive
integer. The name of a file contains at least a . and an extension.
String S consists only of alphanumerical characters (a-z and/or A-Z The name of a directory or sub-directory will not contain a ..
and/or 0-9) and dashes(-).
String S is non-empty.

Time complexity required: O(n) where n is the size of the input


------------------------------ string.
------------------------------
Longest Absolute File Path Notice that a/aa/aaa/file1.txt is not the longest file path, if
------------------------------ there is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.
Suppose we abstract our file system by a string in the following ------------------------------
manner: ------------------------------
Encode and Decode TinyURL
The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: ------------------------------
Note: This is a companion problem to the System Design problem:
dir Design TinyURL.
subdir1
TinyURL is a URL shortening service where you enter a URL such as ------------------------------
https://leetcode.com/problems/design-tinyurl and it returns a short Poor Pigs
URL such as http://tinyurl.com/4e9iAk. ------------------------------

Design the encode and decode methods for the TinyURL service. There There are 1000 buckets, one and only one of them contains poison,
is no restriction on how your encode/decode algorithm should work. the rest are filled with water. They all look the same. If a pig
You just need to ensure that a URL can be encoded to a tiny URL and drinks that poison it will die within 15 minutes. What is the
the tiny URL can be decoded to the original URL. minimum amount of pigs you need to figure out which bucket contains
------------------------------ the poison within one hour.
------------------------------
Coin Change 2
------------------------------ Answer this question, and write an algorithm for the follow-up
general case.
You are given coins of different denominations and a total amount of
money. Write a function to compute the number of combinations that
make up that amount. You may assume that you have infinite number of
each kind of coin. Follow-up:

Note:
You can assume that If there are n buckets and a pig drinking poison will die within m
minutes, how many pigs (x) you need to figure out the "poison"
0 <= amount <= 5000 bucket within p minutes? There is exact one bucket with poison.
1 <= coin <= 5000
the number of coins is less than 500 ------------------------------
the answer is guaranteed to fit into signed 32-bit integer ------------------------------
Minimum Genetic Mutation
------------------------------
A gene string can be represented by an 8-character long string, with
Example 1: choices from "A", "C", "G", "T".

Input: amount = 5, coins = [1, 2, 5] Suppose we need to investigate about a mutation (mutation from
Output: 4 "start" to "end"), where ONE mutation is defined as ONE single
Explanation: there are four ways to make up the amount: character changed in the gene string.
5=5
5=2+2+1 For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
5=2+1+1+1
5=1+1+1+1+1 Also, there is a given gene "bank", which records all the valid gene
mutations. A gene must be in the bank to make it a valid gene
string.
Example 2:
Now, given 3 things - start, end, bank, your task is to determine
Input: amount = 3, coins = [2] what is the minimum number of mutations needed to mutate from
Output: 0 "start" to "end". If there is no such a mutation, return -1.
Explanation: the amount of 3 cannot be made up just with coins of 2.
Note:

Example 3: Starting point is assumed to be valid, so it might not be included


in the bank.
Input: amount = 10, coins = [10] If multiple mutations are needed, all mutations during in the
Output: 1 sequence must be valid.
You may assume start and end string is not the same.

------------------------------

Example 1: LFUCache cache = new LFUCache( 2 /* capacity */ );

start: "AACCGGTT" cache.put(1, 1);


end: "AACCGGTA" cache.put(2, 2);
bank: ["AACCGGTA"] cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
return: 1 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)
Example 2: cache.get(3); // returns 3
cache.get(4); // returns 4
start: "AACCGGTT"
end: "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"] ------------------------------
------------------------------
return: 2 ------------------------------
Longest Palindromic Subsequence
------------------------------

Example 3: Given a string s, find the longest palindromic subsequence's length


in s. You may assume that the maximum length of s is 1000.
start: "AAAAACCC"
end: "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"] Example 1:
Input:
return: 3
"bbbab"

------------------------------ Output:
------------------------------
LFU Cache 4
------------------------------
Design and implement a data structure for Least Frequently Used One possible longest palindromic subsequence is "bbbb".
(LFU) cache. It should support the following operations: get and
put.
Example 2:
Input:

get(key) - Get the value (will always be positive) of the key if the "cbbd"
key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already Output:
present. When the cache reaches its capacity, it should invalidate
the least frequently used item before inserting a new item. For the 2
purpose of this problem, when there is a tie (i.e., two or more keys
that have the same frequency), the least recently used key would be One possible longest palindromic subsequence is "bb".
evicted.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

You might also like