My LeetCode Notebook
My LeetCode Notebook in C++.
Aug 8, 2016
Insert Delete GetRandom O(1) (medium)
1 | // Runtime: 96ms, beat ?% |
Kth Smallest Element in a Sorted Matrix (medium)
1 | // Runtime: 148ms, beat ?% |
July 30, 2016
Bulls and Cows (easy)
1 | // Runtime: 4ms, beat 65.87% |
Roman to Integer (easy)
1 | // Runtime: 36ms, beat 82.16% |
Nim Game (easy)
Notes, n
- 1, 2, 3: win
- 4: lose
- 5: take one stone, win
- 6: take two stones, win
- 7: take three stones, win
- 8: lose
1 | // Runtime: 0ms |
Power of Three (easy)
Solution 1 (learned online)
- This method only works for “Power of
b
“ whereb
is a prime number. - Suppose
0<x=b^a<=INT_MAX
.
Lety
be the maximum power ofb
no larger thanINT_MAX
.
We must havey%x==0
1 | // Runtime: 132ms, beat 75.75% |
Solution 2
1 | // Runtime: 136ms, beat 68.51% |
Power of Four (easy)
Similar to the problem of “Power of Two”, the first two conditions check whether num
is power of two.
If so, we also check whether the only 1
bit is in the right position.
The number of trailing zeros in the binary form should be even).
1 | // Runtime: 8ms, beat 13.80% |
Power of Two (easy)
Naive implementation
1 | // Runtime: 4ms, beat 9.91% |
Smarter solution: Suppose n
is power of two, say n=8
.
- Its binary form looks like
01000
, andn-1
looks like00111
. - Therefore,
n & (n-1)
must be zero.
1 | // Runtime: 4ms, beat 9.91% |
Implement Queue using Stacks (easy)
1 | // Runtime: 0ms |
Implement Stack using Queues (easy)
1 | // Runtime: 0ms |
Compare Version Numbers (easy)
1 | // Runtime: 0ms |
Recursive implementation
July 29, 2016
Binary Tree Level Order Traversal II (easy)
1 | // Runtime: 8ms, beat 25.28% |
Recursive implementation.
1 | // Runtime: 4ms, beat 91.32% |
Intersection of Two Linked Lists (easy)
1 | // Runtime: 48ms, beat 95.28% |
Symmetric Tree (easy)
1 | // Runtime: 4ms, beat 28.55% |
Balanced Binary Tree (easy)
1 | // Runtime: 16ms, beat 17.00% |
Factorial Trailing Zeroes (easy)
We need to find out how many “fives” are there.
1 | // Runtime: 4ms, beat 18.80% |
Pascal’s Triangle II (easy)
1 | // Runtime: 0ms, beat 24.78% |
Pascal’s Triangle (easy)
1 | // Runtime: 0ms, beat 28.29% |
Path Sum (easy)
1 | // Runtime: 12ms, beat 21.69% |
Valid Sudoku (easy)
1 | // Runtime: 12ms, beat 56.30% |
Linked List Cycle (easy)
1 | // Runtime: 12ms, beat 25.00% |
Lowest Common Ancestor of a Binary Search Tree (easy)
1 | // Runtime: 40ms, beat 66.05% |
Number of 1 Bits (easy)
1 | // Runtime: 4ms, beat 60.49% |
Count and Say (easy)
It is unclear what will happen if cnt>9
. The problem description is not clear about this.
1 | // Runtime: 0ms, beat 73% |
Reverse Bits (easy)
1 | // Runtime: 4ms, beat 49.42% |
Longest Common Prefix (easy)
1 | // Runtime: 4ms, beat 53.44% |
Implement strStr() (easy)
Naive implementation
1 | // Runtime: 4ms, beat 33.56% |
ZigZag Conversion (easy)
For each position in the returned string, calculate its original position in s
.
1 | // Runtime: 16ms, beat 76.68% |
Reverse Integer (easy)
1 | // Runtime: 8ms, beat 50.08% |
Another implementation using string
.
1 | // Runtime: 12ms, beat 9.63% |
Valid Parentheses (easy)
1 | // Runtime: 0ms, beat 15.40% |
Length of Last Word (easy)
1 | // Runtime: 0ms, beat 99.33% |
Design Twitter (medium)
1 | // Runtime: 72ms, beat 89.48% |
Peeking Iterator (medium)
1 | // Runtime: 4ms, beat 2.97% |
Binary Search Tree Iterator (medium)
1 | // Runtime: 28ms, beat 15.69% |
A faster but longer implementation: use a fixed length vector as the stack.
1 | // Runtime: 24ms, beat 80.09% |
Wiggle Subsequence (medium)
1 | // Runtime: 0ms |
July 28, 2016
Game of Life (medium)
Solution
- First pass: use one bit to keep the new status.
- Second pass: update status
1 | // Runtime: 3ms, beat 27.28% |
Container With Most Water (medium)
1 | // Runtime: 28ms, beat 11.36% |
Sort Colors (medium)
Notes
- Cannot swap two while!!!!!!!!
1 | // Runtime: 4ms, beat 13.60% |
Kth Largest Element in an Array (medium)
1 | // Runtime: 12ms, beat 87.53% |
Search in Rotated Sorted Array II (medium)
1 | // Runtime: 8ms, beat 27.64% |
Unique Binary Search Trees II (medium)
First implementation, O(2^n)
.
1 | // Runtime: 52ms, beat 0.67% |
Optimized a little bit..
1 | // Runtime: 24ms, beat 39.22% |
Different Ways to Add Parentheses (medium)
First implementation, parse the string first
1 | // Runtime: 12ms, beat 3.62% |
Second implementation, do not parse the string in advance.
1 | // Runtime: 8ms, beat 11.14% |
Search a 2D Matrix II (medium)
1 | // Runtime: 208ms, beat 54.66% |
Search a 2D Matrix (medium)
1 | // Runtime: 12ms, beat 26.53% |
July 27, 2016
Super Ugly Number (medium)
1 | // Runtime: 145ms, beat 45.01% |
Increasing Triplet Subsequence (medium)
1 | // Runtime: 8ms, beat 20.56% |
July 26, 2016
Flatten Binary Tree to Linked List (medium)
1 | // Runtime: 8ms, beat 24.96% |
Verify Preorder Serialization of a Binary Tree (medium)
Notes
- If we see a non-leaf node, we are expecting to see two more nodes in the future.
1 | // Runtime: 4ms, beat 70.41% |
Sum Root to Leaf Numbers (medium)
1 | // Runtime: 4ms, beat 11.58% |
Maximum Subarray (medium)
1 | // Runtime: 8ms, beat 74.15% |
Combination Sum IV (medium)
DP
1 | // Runtime: 4ms, beat ??% |
Triangle (medium)
1 | // Runtime: 8ms, beat 16.07% |
Ugly Number II (medium)
Dynamic programming
1 | // Runtime: 16ms, beat 61.32% |
Delete Node in a Linked List (easy)
1 | // Runtime: 16ms, beat 15.47% |
Move Zeroes (easy)
1 | // Runtime: 20ms, beat 27.77% |
Remove Element (easy)
1 | // Runtime: 4ms, beat 14.16% |
Populating Next Right Pointers in Each Node II :hard:
1 | // Runtime: 36ms, beat 78.42% |
Populating Next Right Pointers in Each Node (medium)
1 | // Runtime: 24ms, beat 50.20% |
Find Peak Element (medium)
Binary search.
1 | // Runtime: 4ms, beat 69.74% |
Same Tree (easy)
1 | // Runtime: 12ms, beat 17.62% |
Valid Anagram (easy)
1 | // Runtime: 12ms, beat 65.57% |
July 25, 2016
Lowest Common Ancestor of a Binary Tree (medium)
1 | // Runtime: 27ms, beat 40.83% |
Contains Duplicate II (easy)
1 | // Runtime: 32ms, beat 49.89% |
Contains Duplicate (easy)
An awesome one-line code from the discussion board.
1 | // Runtime: 48ms, beat 54.45% |
Contains Duplicate III (medium)
Notes
- OK:
m.lower_bound(value)
1 | // Runtime: 48ms, beat 36% |
Kth Largest Element in an Array (medium)
Notes
- Modify
k
: 1st largest,k=0
!!!!!!!!
1 | // Runtime: 12ms, beat 82.53% |
Binary Tree Zigzag Level Order Traversal (medium)
1 | // Runtime: 4ms, beat 17% |
Pow(x, n) (medium)
Be careful of the possible overflow while writing n=-n
.
1 | // Runtime: 4ms, beat 19.88% |
Group Anagrams (medium)
1 | // Runtime: 64ms, beat 86.22% |
Decode Ways (medium)
Dynamic programming.
1 | // Runtime: 4ms, beat 14.34% |
4Sum (medium)
First implementation, O(n^3)
, an extension of the solution to the 3Sum
problem.
1 | // Runtime: 93ms, beat 51.11% |
(Will work on the O(nlogn)
implementation later.)
3Sum (medium)
1 | // Runtime: 56ms, beat 54.56% |
Remove Duplicates from Sorted List II (medium)
1 | // Runtime: 12ms, beat 10.02% |
Divide Two Integers (medium)
1 | // Runtime: 12ms, beat 9.72% |
Fraction to Recurring Decimal (medium)
1 | // Runtime: 4ms, beat 8% |
Convert Sorted List to Binary Search Tree (medium)
Notes
- Get the length of the sorted list.
- Use a reference of pointer (
ListNode *&head
) to keep track of the current list node.
1 | // Runtime: 28ms, beat 66.89% |
Reverse Linked List II (medium)
1 | // Runtime: 4ms, beat 4.97% |
Palindrome Partitioning II :hard:
1 | // Runtime: 24ms, beat 73.17% |
Palindrome Partitioning (medium)
1 | // Runtime: 16ms, beat 62.76% |
July 24, 2016
Combinations (medium)
1 | // Runtime: 88ms, beat 91.14% |
Permutation Sequence (medium)
1 | // Runtime: 3ms, beat 48.69% |
Permutations II (medium)
1 | // Runtime: 60mb, beat 5.67% |
Combination Sum II (medium)
1 | // Runtime: 16ms, beat 41.90% |
Combination Sum (medium)
Notes
- Be careful when write dfs (e.g.,
i
and the search position).
1 | // Runtime: 20ms, beat 56.38% |
Guess Number Higher or Lower II (medium)
Dynamic programming
1 | // Runtime: 64ms, beat 36.59% |
Guess Number Higher or Lower (easy)
1 | // Runtime: 0ms, beat 12.53% |
Gray Code (medium)
1 | // Runtime: 4ms, beat 22.89% |
Gas Station (medium)
Greedy: O(n)
- The gas station:
[0, 1, ..., n-2, n-1, 0, 1, ..., n-2, n-1, ...]
- If we cannot reach the “next station”, restart at the “next station”.
- The last possible starting gas station is
n-1
.
If we are standing at the secondn-2
station, and we cannot reach thenxt_station
, we return-1
.
1 | // Runtime: 8ms, beat 14.53% |
Remove Duplicates from Sorted List II (medium)
1 | // Runtime: 12ms, beat 81.03% |
Rotate Image (medium)
1 | // Runtime: 4ms, beat 18.64% |
Minimum Height Trees (medium)
Solution:
- Perform level-by-level BFS, from leaves to the inside nodes.
- The last level should contain one or two nodes, they are what we want.
1 | // Runtime: 108ms, beat 68.94% |
July 23, 2016
Longest Increasing Subsequence (medium)
If duplicates elements are allowed in the LIS,
we should replace nums[i]>f[max_len-1]
by nums[i]>=f[max_len-1]
,
and replace lower_bound
by upper_bound
.
1 | // Runtime: 4ms, beat 62.20% |
Permutations (medium)
DFS
1 | // Runtime: 12ms, beat 76.80% |
Next Permutation (medium)
Notes
- Find the largest
i
so thatnums[i-1] < nums[i]
. (e.g.,7 8 6 [9,i] 8 7 2
) - If we cannot find such an
i
, we sort the entirenums
and return. - Otherwise, find the smallest value
nums[j]
innums[i..last]
that is larger thannums[i]
(e.g,7
in the above example). - Swap
nums[i-1]
andnums[j]
, and sortnums[i..last]
.
1 | // Runtime: 12ms, beat 21.72% |
Repeated DNA Sequences (medium)
First implementation, use an unordered_map
to keep the hash values.
1 | // Runtime: 116ms, beat 63.84% |
Faster, use larger spaces to keep the hash values.
1 | // Runtime: 12ms, beat 97.07% |
Additive Number (medium)
Be careful about the length of the string when using substr
.
1 | // Runtime: 0ms |
Majority Element II (medium)
1 | // Runtime: 20ms, beat 36.68% |
July 22, 2016
Set Matrix Zeroes (medium)
O(1)
extra space:
- Find a position
(x,y)
so thatmatrix[x][u]==0
. - If there is no such position, done.
- Use that row and column to mark rows and columns that we have to reset. Then, reset.
1 | // Runtime: 77ms, beat 18.93% |
Jump Game (medium)
Greedy, keep the maximum distance that we can reach.
1 | // Runtime: 16ms |
Unique Paths II (medium)
1 | // Runtime: 4ms |
Minimum Path Sum (medium)
1 | // Runtime: 12ms, beat 26.71% |
Unique Paths (medium)
1 | // Runtime: 0ms, beat % |
Basic Calculator II (medium)
1 | // Runtime: 36ms, beat 31.78% |
Word Break (medium)
1 | // Runtime: 4ms, beat 85.01% |
Sort List (medium)
1 | // Runtime: 67ms, beat 27.84% |
Reconstruct Itinerary (medium)
1 | // Runtime: 40ms, beat 37.67% |
Summary Ranges (medium)
1 | // Runtime: 0ms |
Coin Change (medium)
DP
1 | // Runtime: 132ms, beat 67.30% |
Clone Graph (medium)
Notes
itr
= somemap.find(key)- Use
itr->second
to get the value, not*itr
!!!!!!!!!!!
1 | // Runtime: 72ms, beat 94.46% |
Maximal Square (medium)
1 | // Runtime: 12ms, beat 36.48% |
Evaluate Reverse Polish Notation (medium)
Be careful when check whether a string is an integer.
1 | // Runtime: 16ms, beat 34.14% |
Restore IP Addresses (medium)
Should double check whether the leading zero in the returned address is okay.
1 | // Runtime: 0ms, beat 89.18% |
Longest Palindromic Substring (medium)
Naive check.
1 | // Runtime: 76ms, beat 51.98% |
Wiggle Sort II (medium)
This is hard. >.
1 | // Runtime: 112ms with nth_element |
Reorder List (medium)
Ideas
- Find the middle element
- Reverse the second half
- Merge two lists
1 | // Runtime: 64ms, beat 51.24% |
Rotate List (medium)
If k<len
, we only need to scan the list in one pass.
1 | // Runtime: 8ms, beat 85.93% |
Slower, clearer, always two passes.
1 | // Runtime: 12ms, beat 9.38% |
Spiral Matrix II (medium)
1 | // Runtime: 4ms |
Spiral Matrix (medium)
1 | // Runtime: 0ms |
Maximum Product Subarray (medium)
Greedy
- Get the product of a contiguous sequence that does not contain zero.
- If the product is negative, try to remove the first few elements or
the last few elements of the sequence so that the product is positive.
1 | // Runtime: 8ms, beat 8.08% |
Simplify Path (medium)
1 | // Runtime: 8ms, beat 54.92% |
Range Sum Query 2D - Immutable (medium)
1 | // Runtime: 24ms, beat 49.76% |
Validate Binary Search Tree (medium)
Notes
- Be careful about the overflow/underflow problem!!!!!!
- Don’t forget
return
.
1 | // Runtime: 16ms, beat 14.08% |
Largest Number (medium)
First implementation, O(1)
extra space.
1 | // Runtime: 20ms, beat 28.94% |
Second implementation, O(n)
extra spaces, faster.
1 | // Runtime: 8ms, beat 59.61% |
Climbing Stairs (easy)
1 | // Runtime: 0ms |
July 21, 2016
Single Number III (medium)
Learned from the discussion board.
Notes
- Get
all_xor
, xor of all values. At least one bit ofall_xor
is one. - Find some bit in
all_xor
is one.
Separate numbers into two groups according to that bit.
Each group contains one result.
- Remember to initialize all variables!!!!!!!
1 | // Runtime: 16ms, beat 87.74% |
Counting Bits
1 | // Runtime: 80ms, beat 97.66% |
Single Number (medium)
1 | // Runtime: 20ms, beat 28.40% |
Top K Frequent Elements (medium)
Notes
- By default,
priority_queue
is a MAXHEAP!!!!
1 | // Runtime: 36ms, beat 75.54% |
Product of Array Except Self (medium)
1 | // Runtime: 60ms, beat 54.88% |
Integer Break (medium)
Notes:
- Be careful about the corner cases!
pow
returnsdouble
!
1 | // Runtime: 0ms |
Missing Number (medium)
Naive method
1 | // Runtime: 32ms, beat 91.71% |
Don’t think too much…..
1 | // Runtime: 36ms, beat 30.08% |
Bit manipulation
Binary Tree Preorder Traversal (medium)
1 | // Runtime: 4ms, beat 0.60% |
Maximum Product of Word Lengths (medium)
For each word, construct a “sketch” indicating appearances of characters.
Then, we can compare any two words fast.
1 | // Runtime: 112ms, beat 88.66% |
Integer to Roman (medium)
1 | // Runtime: 32ms, beat 66.30% |
Odd Even Linked List (medium)
Don’t forget to set tail_even->next = NULL
!!!!!!!!!!!!!!!!!!!!!!!!!!.
1 | // Runtime: 20ms, beat 20.18% |
Kth Smallest Element in a BST (medium)
1 | // Runtime: 20ms, beat 72.56% |
Generate Parentheses (medium)
Notes:
- Don’t forget
<char>
instack<char>
….
1 | // Runtime: 0ms, beat 41.55% |
Single Number II (medium)
Let result
be the result. For each bit of result
,
it is 1
if and only if the number of occurrences of 1
in that position is 1+3x
.
1 | // Runtime: 12ms, beat 74.96% |
Convert Sorted Array to Binary Search Tree (medium)
How to proof?
1 | // Runtime: 16ms, beat 74.11% |
Unique Binary Search Trees (medium)
The inner loop could be further speedup…
1 | class Solution { |
Search Insert Position (medium)
Binary search.
1 | // Runtime: 8ms, beat 15.00% |
Combination Sum III (medium)
Simple DFS.
1 | // Runtime: 0ms |
Rectangle Area (easy)
1 | // Runtime: 32ms, beat 58.47% |
July 15, 2016
3Sum Closest (medium)
First implementation O(n^2)
.
1 | // Runtime: 28ms, beat 15.06% |
July 14, 2016
N-Queens II :hard:
1 | // Runtime: 0ms, beat 90.19% |
N-Queens :hard:
1 | // Runtime: 0ms, beat 91.88% |
Swap Nodes in Pairs (easy)
1 | // Runtime: 4ms, beat 3.56% |
Reverse Nodes in k-Group :hard:
Iterative implementation
1 | // Runtime: 24ms, beat 54.68% |
Recursive implementation
1 | // Runtime: 28ms, beat 12.09% |
Regular Expression Matching :hard:
Search with logged results
1 | // Runtime: 12ms, beat 73.25% |
Wildcard Matching :hard:
First (slow) implementation
1 | // Runtime: 1272ms, beat 34.60% |
The second (faster) implementation (dynamic programming)
1 | // Runtime: 477ms, beat 42.93% |
A a trick.
1 | // Runtime: 36ms, beat 53.63% |
Text Justification :hard:
1 | // Runtime: 0ms |
July 13, 2016
String to Integer (atoi) (easy)
Max Points on a Line :hard:
Choose a node as one point of the line and check other points. O(n^2)
1 | // Runtime: 8ms, beat 99.44% |
July 11, 2016
Binary Tree Level Order Traversal (easy)
1 | // Runtime: 8ms, beat 11.75% |
Word Ladder II :hard:
Fast implementation from the discussion… (My first implementation takes 500ms…)
Ideas
- Double-ended BFS. Visited words are remove from the dictionary.
- Recover the paths
1 | // Runtime: 85ms, beat 86.38% |
July 10, 2016
Path Sum II (medium)
1 | // Runtime: 16ms, beat 47.89% |
Binary Tree Paths (easy)
1 | // Runtime: 4ms, beat 22.11% |
Reverse Vowels of a String (easy)
1 | // Runtime: 12ms, beat 75.90% |
July 9, 2016
Binary Tree Right Side View (medium)
First implementation, traverse level by level.
1 | // Runtime: 8ms, beats 3.36% |
A better implementation
1 | // Runtime: 4ms, beats 27.47% |
Number of Islands (medium)
1 | // Runtime: 8ms, beats 53.68% |
No recursion, 12ms
1 | class Solution { |
Minimum Size Subarray Sum (medium)
First implementation: O(n)
, two pointers.
1 | // Runtime: 4ms |
Second implementation, O(n log n)
, binary search.
1 | // Runtime: 8ms |
Third implementation: O(n log n)
, binary search.
1 | // Runtime: 12ms |
Count Primes (easy)
First implementation
1 | // Runtime: 376ms, 20.85% |
Second implementation
1 | // Runtime: 56ms, 80.83% |
Search in Rotated Sorted Array :hard:
Ideas:
- Find the index of the minimum element in the array.
- Normal binary search in the proper range of the vector>
1 | // Runtime: 4ms |
Find Minimum in Rotated Sorted Array II :hard:
The worst case is something like this [1,1,1,1,0,1,1,1,1,1]
.
I think we have to scan over the complete vector so to figure whether there is anything smaller than 1
.
The solution is a variation of the binary search.
1 | // Runtime: 8ms, 23.35% |
Find Minimum in Rotated Sorted Array (medium)
1 | // Runtime: 4ms, beats 23.06% |
Min Stack (easy)
An implementation using vector. I don’t know whether I should use vectors, LOL.
1 | // Runtime: 56ms, beats 25.33% |
House Robber III (medium)
1 | // Runtime: 12ms, beats 76.88% |
House Robber II (medium)
We need to decide whether we rob the first house.
The code could be shorter, I know I don’t have to use the vector money
.
1 | // Runtime: 0ms |
House Robber (easy)
Dynamic programming
1 | // Runtime: 0ms |
Another implementation with O(1)
extra space.
1 | // Runtime: 0ms |
First Bad Version (easy)
Oh, maybe I should always let “left, right, and middle” be long long…
1 | // Runtime: 0ms |
H-Index II (medium)
1 | // Runtime: 12ms, beat 38.31% |
H-Index (medium)
1 | // Runtime: 4ms, beat 21.37% |
July 8, 2016
Reverse Words in a String (medium)
Ideas
- First, remove the complete string
- Then, reverse each word and remove duplicated spaces.
1 | // Runtime: 8ms, beat 45.83% |
Surrounded Regions (medium)
First implementation
- Fill all surrounded regions with
X
, fill all non-surrounded regions with@
@
->X
1 | // Runtime: 20ms, beat 32.19% |
Second implementation
- Copy
board
asvisited
- From four boundaries of
visited
, fill non-surrounded ‘O’ by ‘V’. - Fill surrounded regions of
board
.
1 | // Runtime: 20ms, beat 32.19% |
Find K Pairs with Smallest Sums (medium)
1 | // Runtime: 20ms, beat ?(too new)% |
Excel Sheet Column Number (easy)
1 | class Solution { |
Excel Sheet Column Title (easy)
Recursion
1 | // Runtime: 0ms |
Iteration
1 | // Runtime: 0ms |
Merge Intervals :hard:
Sort and merge.
1 | // Runtime: 26.79, beat % |
July 7, 2016
Super Pow (medium)
Key observation: ab mod c == (a mod c)(b mod c) mod c
1 | // Runtime: 12ms, beat ?% |
Intersection of Two Arrays II (easy)
First implementation.
1 | // Runtime: 12ms, beat 37.52% |
Second implementation. It is faster than the first implementation.
I guess this is because one of the vector is small compared to the other.
1 | // Runtime: 8ms, beat 82.75% |
Intersection of Two Arrays (easy)
1 | // Runtime: 12ms, beat 42.47% |
Max Sum of Rectangle No Larger Than K :hard:
To illustrate, suppose the number of rows n
is less than m
.
- Suppose the first row is
r1
, the last row isr2
, and the last column iscol
(O(n*n*m)
choices). - We check whether we can remove the first few columns so that the sum is no larger than
k
(binary search,O(log m)
). - The complexity is
O(n*n*m*logm)
.
If n>m
, the solution is similar, but with complexity O(m*m*n*log n)
.
1 | // Runtime: 976ms, beat 96.52% |
Valid Perfect Square (medium)
Binary search.
1 | // Runtime: 0ms |
Sum of Two Integers (easy)
1 | // Runtime: 0ms |
CLOSED:
Flatten Nested List Iterator (medium)
We use a stack to keep track of the status.
When hasNext()
is called, we make sure that the top element of the stack points to the next integer.
1 | // Runtime: 32ms, beat 64.43% |
June 25, 2016
Word Pattern (easy)
BIJECTION!
1 | // Runtime: 0ms |
June 24, 2016
Perfect Squares (medium)
I learned this cute idea of using a static vector in the discussion board.
The running time decreased from around 400ms to 50ms.
1 | // Runtime: 52ms, beat 83.71% |
Water and Jug Problem (medium)
I have the problem description….
CLOSED:
1 | // Runtime: 2ms |
Minimum Depth of Binary Tree (easy)
Got WA for two times…..
1 | // Runtime: 12ms, beat 15.10% |
Course Schedule II (medium)
Pretty much same as the previous solution.
1 | // Runtime: 24ms, beat 85.63% |
Course Schedule (medium)
Return true if and only if there is no cycle in the graph.
1 | // Runtime: 20ms, beat 86.54% |
Construct Binary Tree from Inorder and Postorder Traversal (medium)
Pretty much same as the previous problem.
1 | // Runtime: 24ms, beat 71.64% |
Construct Binary Tree from Preorder and Inorder Traversal (medium)
Use a map to record the position of each value in the “inorder”.
1 | // Runtime: 24ms, beat 79.85% |
June 23, 2016
Binary Tree Inorder Traversal (medium)
1 | // Runtime: 0ms |
May 6, 2016
Range Sum Query - Mutable (medium)
Use a binary interval tree.
1 | // Runtime: 64ms, beat 100.0% |
Range Sum Query - Immutable (easy)
Simple (tricky) dynamic programming…
1 | // Runtime: 28ms, beat 100.0% |
Isomorphic Strings (easy)
Oh, I should have read the problem description more carefully…
1 | // Runtime: 8ms |
Count Complete Tree Nodes (medium)
A recurive implementation. The key idea is to check whether the left tree is perfect.
1 | // Runtime: 196ms, beat 43.99% |
A faster implementation, calculate height
(ane check whether the left subtree is perfect) iteratively.
1 | // Runtime: 84ms, beat 91.5% |
Palindrome Number (easy)
Remarks
- Negative integers are not palindrome numbers.
- Non-zero multiples of 10 are not palindrome numbers.
1 | // Runtime: 72ms, beat 81.26% |
Reverse Linked List (easy)
Iteratively:
1 | // Runtime: 8ms |
Recursively
1 | // Runtime: 8ms |
Palindrome Linked List (easy)linked_list:
First, use two pointers to fine the first node of the second half of the list. For example:
- 1 2 3 4(this one) 5 6
- 1 2 3 2(this one) 1
Then, reverse the second half of the list.
Finally, compare the first half and the reversed second half.
1 | // Runtime: 28ms |
Create Maximum Number :hard:
High level ideas:
- Enumerate all valid length pair
(k1, k2)
so thatk1+k2==k
- For each
(k1, k2)
- From
nums1
, find the maximum substringsub1
with lengthk1
- From
nums2
, find the maximum substringsub2
with lengthk2
- Concatenate
sub1
andsub2
and get a solution.
- From
How to find the maximum substring of nums
with length k
?
- Maintain a stack
sub
(initially empty) - Scan
nums
, suppose we are now atnums[i]
- Pop the top of
sub
, if- the remaining part of
nums
contains enough digits to fillsub
nums[i]
is larger than the “top” element ofsub
- the remaining part of
- Push
nums[i]
intosub
- Pop the top of
1 | // Runtime: 60ms, beat 75.2% |
Bulb Switcher (medium)
Let’s first see two examples.
- 9 = 1 * 9 = 3 * 3
- 60 = 1 * 60 = 2 * 30 = 3 * 20 = 4 * 15 = 5 * 12 = 6 * 10
One could verify that
- Bulb with a square number id: on
- Bulb with non-square number id: off
Solution: Given n, return the number of square numbers between 1 and n.
1 | // Runtime: 0ms |
April 27, 2016
Add Digits (easy)
A straightforward solution.
1 | // Runtime: 12ms |
A smarter solution learned from the discussion board.
1 | // Runtime: 8ms |
April 25, 2016
Number of Digit One :hard:math:
Ideas:
- Let’s write n as
n=[n1][x][n2]
(e.g.,12345 = [12][3][45]
). - We want to now how many non-negative integers less than or equal to n looks like
[len(n1)][x][len(n2)]
.
Here, the length of the first part equals to the length of n1
.
Here, the length of the last part equals to the length of n2
.
- How many?
- Suppose the first part is in
[0, n1-1]
, there aren1*pow(10, len(n2))
such integers. - Suppose the second part is
n1
.- If
x==1
, there aren2
such integers. - If
x>1
, there arepow(10, len(n2))
such integers. - If
x==0
, there is no such integers.
- If
- Suppose the first part is in
1 | // Runtime: 0ms |
Reverse String (easy)
A super easy problem before dinner…
1 | class Solution { |
Word Ladder (medium)
Solution: BFS
1 | // Runtime: 268ms, beat 72.66% |
Word Search (medium)
Solution
- DFS
- Use
board
to do the backtrack.
1 | // Runtime: 28ms, beat 71.06% |
Word Search II :hard:trie:
Solution:
- Build a Trie tree, and use DFS to search the board.
- Codes without the deconstruction of Trie can pass all the test cases. But I don’t think that’s good.
1 | // Without deconstruction: 61, beat 81.16% |
Add and Search Word - Data structure design (medium)trie:
Solution: Build a Trie tree to store words, and use DFS to search the work.
1 | // Runtime: 80ms, beat 79.16% |
Implement Trie (Prefix Tree) (medium)trie:
Notes:
- Using
TrieNode* next[26]
is faster thanvector<TrieNode*> next
. - Codes without the deconstruction of Trie can pass all the test cases. But I don’t think that’s good.
1 | // Without deconstruction: 56ms, beat 75.89% |
April 23, 2016
Letter Combinations of a Phone Number (medium)dfs:
1 | // Runtime: 0ms |
Candy :hard:greedy:
Greedy
- Initially, every kid has 1 candy.
- Scan the ratings from left to right, if
rantings[i]>ratings[i-1]
, make surecandy[i]>candy[i-1]
. - Scan the ratings from the right to left, if
rantings[i]>ratings[i+1]
, make surecandy[i]>candy[i+1]
.
1 | // Runtime: 40ms, beat 22.09% |
April 22, 2016
Remove Duplicates from Sorted Array II (medium)
1 | // Runtime: 16ms, beat 62.74% |
Remove Duplicates from Sorted Array (easy)
1 | // Runtime: 32ms, beat 31.5% |
Longest Valid Parentheses :hard:stack:
Solution
- First scan
- Use a stack to store indices of parentheses.
- If the current char is
")"
and the char corresponds to the stack top is"("
, pop the stack.
- Second scan
- Between two “unmatched” parentheses, there is a valid parentheses substring.
1 | // Runtime: 12ms, beat 15.07% |
Valid Palindrome (easy)string:
Easy one.
1 | // Runtime: 12ms, beat 40.64% |
Best Time to Buy and Sell Stock with Cooldown
DP
buy[i]
: at the end of timei
, we have bought stocksell[i]
: at the end of timei
, we have sold our stock- Space:
O(1)
instead ofO(n)
1 | // Runtime: 8ms, beat 13.36% |
Best Time to Buy and Sell Stock III :hard:dp:
One solution is to use the codes for “Best Time to Buy and Sell Stock IV”. But the codes could be shorter.
1 | // Runtime: 8ms, beat 66.62% |
Best Time to Buy and Sell Stock IV :hard:dp:
Notes
- DP:
O(2k)
space,O(nk)
time. - For the special case where
k>=prices.size()/2
, we should use greedy. Because DP is too slow. (TLE for many times…)
1 | // Runtime: 12ms, beat 21.44% |
Best Time to Buy and Sell Stock II (medium)greedy:
Greedy solution, buy at lower prices and sell at higher prices.
It is “okay” to first sell and immediately buy at a time slot.
Because it is equivalent to doing nothing at that time slot.
1 | // Runtime: 8ms, beat 17% |
Best Time to Buy and Sell Stock (easy)dp:
Idea: keep the lowest price seen so far.
If we sell at time i
, we buy with the lowest price before time i
.
1 | // Runtime: 8ms, beat 20% |
April 21, 2016
Ugly Number (easy)
Super easy.. Before dinner..
1 | // Runtime: 8ms |
Longest Substring Without Repeating Characters (medium)
Keep two pointers. One points to the start of the substring, one points to the end of it.
Move the first pointer if there are repeating characters.
1 | // Runtime: 16ms, beat 67.72% |
Multiply Strings (easy)
A straightforward implementation.
1 | // Runtime: 28ms, beat 17.99% |
Improvement (no speedup, don’t understand)
Ideas
- Initialize result with 0 instead of ‘0’
- Use
tmp-carry*10
instead oftmp%10
. (Discussion board:%
is slower than subtraction and multiply)
1 | // Runtime: 32ms |
Add Binary (easy)math:string:
1 | // Runtime: 4ms, beat 21.14% |
Add Two Numbers (medium)
I learned this implementation from the discussion board.
It seems like using a preHead
makes things easier.
It’s basically a dummy head.
For example, I don’t have to check whether head==NULL
or not.
1 | // Runtime: 36ms, beat 63.7% |
Bitwise AND of Numbers Range (medium)
Try and set every bit of n to zero. If it the new value is no smaller than m, AND it with the current result.
1 | // Runtime: 68ms, beat 56.73% |
Find this solution from the discussion board…. Awesome!
An explanation from the discussion board.
- If n>m, the final bit of the result will be zero.
Thus we shift both numbers down to the right one slot,
and recursively consider if those final digits match.
- When we finally find a non-zero match (n==m==1),
it must have occurred on the slot in the position shifted left,
as many times as we have shifted right. Thus the way the program works.
1 | // Runtime: 72ms |
Sqrt (medium)
Use binary search to find the square root of an integer.
Some notes
- Be careful about the overflow problem…
- Check the stopping criteria…
1 | // Runtime: 8ms, beat 39.64% |
April 20, 2016
Inverse Binary Tree (easy)
A super easy one…
1 | // Runtime: 0ms |
Two Sum (easy)
A simple but slow solution using unordered_map
.
P.S. Use unordered_map
instead of map
, if possible.
1 | // Runtime: 16ms, beat 55.48% |
Improvement: Insert numbers into map lazily (no speedup).
1 | // Runtime: 16ms, beat 55.48% |
April 19, 2016
Plus One (easy)
1 | //Runtime: 4ms, beat 3.4% (almost every one has this runtime) |
Sbusets II (medium)
Ideas: Sort the numbers first.
If a number equals to its previous one, we only expand subsets generated in the previous iteration.
Otherwise, we expand all subsets we have generated.
1 | //Runtime: 12 ms, beat 18.57% |
Speedup: Resize results
instead of pushing back.
Note: <<
has lower precedence than -
.
1 | // Runtime: 8 ms, beat 71.92% |
Subsets (medium)
I think this is an easy problem… (Don’t forget the empty set.)
1 | // Runtime: 4 ms, beat 83.38% |
Insertion Sort List (medium)
I think this is an easy problem…
1 | // Runtime: 24 ms, beat 87.82% |
Remove Linked List Elements (easy)
1 | // Runtime: 36 ms, beat 8.25% |
The recursive version:
1 | // Runtime: 36 ms, beat 8.25% |
Merge Two Sorted Lists (easy)
1 | // Runtime: 408 ms, beat 82.07% |
Merge k Sorted Lists :hard:
1 | // Runtime: 424 ms, beat 37.5% |
Second solution, I learned this recursive implementation from the discussion board.
1 | // Runtime: 408 ms, beat 82.07% |
April 16, 2016
Rotate Array (easy)
1 | // Runtime: 24 ms |
November 2015
Happy Number (easy)
Don’t know how to write faster codes. Using set
instead of unordered_set
also runs in 4ms.
1 | // Runtime: 4 ms |
Maximum Depth of Binary Tree (easy)
1 | // Runtime: 8ms |
The following codes also run in 8ms.
1 | /** |
Remove Nth Node From End of List (easy)
1 | /** |
Search for a Range
A lazy version using STL.
1 | // Runtime 12ms, beats 9.55% |
Write lower bound function.
1 | // Runtime 12ms, beats 9.55% |
Palindrome Partitioning II :hard:
Use is_pal[i][j]
to denote whether s[i..j]
is a palindrome. Then use dynamic
programming to find the minimum cut.
1 | class Solution { |