Of course, question is super easy, but I'm curious.

I know that this cannot be measured precisely, but everyone can estimate some range of time to solve problem..

For example:

- Level Easy, Min= 15 min, Max= 1h, Avg = 30 min.

Could you describe your time solving?

]]>Yes, we are considering to use the remaining time for the count down which does not base on your local timestamp. ]]>

class Solution(object):

### my own code, run time is O(N*N)

def fourSum(self, nums, target):

"""

:type nums: List[int]

:type target: int

:rtype: List[List[int]]

"""

#nums.sort()

length = len(nums)

d = dict()

for i in xrange(length):

for j in xrange(i+1, length):

val = nums[i] + nums[j]

if val in d:

d[val].append((i,j))

else:

d[val] = [(i,j)]

res = set()

for k in d:

val = target - k

if val in d:

vlist = d[val]

klist = d[k]

for (i,j) in vlist:

for (l,m) in klist:

ilist = [i,j,l,m]

if len(set(ilist)) != len(ilist):

continue

mylist = [nums[i], nums[j], nums[l], nums[m]]

mylist.sort()

res.add( tuple(mylist) )

return list(res)

Clever but the running time doesn't decrease obviously. And the method is not general, just for 4 sum questions.

However, it's enlightened

]]>https://github.com/fabriziodemaria/LeetCode_To_GitHub

Thank you!

Fabrizio

]]>DFS handles an explicit tree.While Backtracking handles an implicit tree

Difference 2:

Depth First Search is a special type of backtracking algorithmic design paradigm where the process of backtracking takes place in the leaf nodes. In case of backtracking,the algorithm also rejects the useless branch of the state-space tree.This is why DFS maintains the entire tree structure while Backtracking maintaines a pruned tree

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. For most other tasks, modern programming languages allow the programmer to work directly with abstractions instead of bits that represent those abstractions. Source code that does bit manipulation makes use of the bitwise operations: AND, OR, XOR, NOT, and bit shifts.

Bit manipulation, in some cases, can obviate or reduce the need to loop over a data structure and can give many-fold speed ups, as bit manipulations are processed in parallel, but the code can become more difficult to write and maintain.

At the heart of bit manipulation are the bit-wise operators & (and), | (or), ~ (not) and ^ (exclusive-or, xor) and shift operators a << b and a >> b.

There is no boolean operator counterpart to bitwise exclusive-or, but there is a simple explanation. The exclusive-or operation takes two inputs and returns a 1 if either one or the other of the inputs is a 1, but not if both are. That is, if both inputs are 1 or both inputs are 0, it returns 0. Bitwise exclusive-or, with the operator of a caret, ^, performs the exclusive-or operation on each pair of bits. Exclusive-or is commonly abbreviated XOR.

- Set union A | B
- Set intersection A & B
- Set subtraction A & ~B
- Set negation ALL_BITS ^ A
- Set bit A |= 1 << bit
- Clear bit A &= ~(1 << bit)
- Test bit (A & 1 << bit) != 0
- Extract last bit A&-A or A&~(A-1) or x^(x&(x-1))
- Remove last bit A&(A-1)
- Get all 1-bits ~0

Count the number of ones in the binary representation of the given number

```
int count_one(int n)
{
while(n)
{
n = n&(n-1);
count++;
}
return count;
}
```

Is power of four (actually map-checking, iterative and recursive methods can do the same)

```
bool isPowerOfFour(int n)
{
return n==1 || (n>1 && (n&-n)==n && (n&0x2aaaaaab)==0);
//n&0x2aaaaaab used to make sure the 1-bit lies in the right position - power of four;
}
bool isPowerOfFour(int n)
{
return !(n&(n-1)) && (n&0x55555555);
//check the 1-bit location;
}
```

`^`

tricksUse `^`

to remove even exactly same numbers and save the odd, or save the distinct bits and remove the same.

Use `^`

and `&`

to add two integers

```
int getSum(int a, int b)
{
return b==0? a:getSum(a^b, (a&b)<<1); //be careful about the terminating condition;
}
```

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. (Of course, you can do this by math.)

```
int missingNumber(vector<int>& nums)
{
int ret = 0;
for(int i = 0; i < nums.size(); ++i)
{
ret ^= i;
ret ^= nums[i];
}
return ret^=nums.size();
}
```

`|`

tricksKeep as many as possible 1-bits

Find the largest power of 2 (most significant bit in binary form), which is less than or equal to the given number N.

```
long largest_power(long N)
{
//changing all right side bits to 1.
N = N | (N>>1);
N = N | (N>>2);
N = N | (N>>4);
N = N | (N>>8);
N = N | (N>>16);
return (N+1)>>1;
}
```

`&`

tricksJust selecting certain bits

Reversing the bits in integer

```
x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);
```

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4.

```
int rangeBitwiseAnd(int m, int n)
{
int a = 0;
while(m != n)
{
m >>= 1;
n >>= 1;
a++;
}
return m<<a;
}
```

All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.

For example,

Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT",

Return: ["AAAAACCCCC", "CCCCCAAAAA"].

```
class Solution {
public:
vector<string> findRepeatedDnaSequences(string s)
{
int sLen = s.length();
vector<string> v;
if(sLen < 11) return v;
char keyMap[1<<21]{0};
int hashKey = 0;
for(int i = 0; i < 9; ++i) hashKey = (hashKey<<2) | (s[i]-'A'+1)%5;
for(int i = 9; i < sLen; ++i)
{
if(keyMap[hashKey = ((hashKey<<2)|(s[i]-'A'+1)%5)&0xfffff]++ == 1)
v.push_back(s.substr(i-9, 10));
}
return v;
}
};
```

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. (bit-counting as a usual way, but here we actually can adopt sorting and Moore Voting Algorithm)

```
int majorityElement(vector<int>& nums)
{
int len = sizeof(int)*8, size = nums.size();
int count = 0, mask = 1, ret = 0;
for(int i = 0; i < len; ++i)
{
count = 0;
for(int j = 0; j < size; ++j)
if(mask & nums[j]) count++;
if(count > size/2) ret |= mask;
mask <<= 1;
}
return ret;
}
```

Given an array of integers, every element appears three times except for one. Find that single one. (Still this type can be solved by bit-counting easily.)

```
//inspired by logical circuit design and boolean algebra;
//counter - unit of 3;
//current incoming next
//a b c a b
//0 0 0 0 0
//0 1 0 0 1
//1 0 0 1 0
//0 0 1 0 1
//0 1 1 1 0
//1 0 1 0 0
//a = a&~b&~c + ~a&b&c;
//b = ~a&b&~c + ~a&~b&c;
//return a|b since the single number can appear once or twice;
int singleNumber(vector<int>& nums)
{
int t = 0, a = 0, b = 0;
for(int i = 0; i < nums.size(); ++i)
{
t = (a&~b&~nums[i]) | (~a&b&nums[i]);
b = (~a&b&~nums[i]) | (~a&~b&nums[i]);
a = t;
}
return a | b;
}
;
```

- result after shifting left(or right) too much is undefined
- right shifting operations on negative values are undefined
- right operand in shifting should be non-negative, otherwise the result is undefined
- The & and | operators have lower precedence than comparison operators

All the subsets

A big advantage of bit manipulation is that it is trivial to iterate over all the subsets of an N-element set: every N-bit value represents some subset. Even better, if A is a subset of B then the number representing A is less than that representing B, which is convenient for some dynamic programming solutions.

It is also possible to iterate over all the subsets of a particular subset (represented by a bit pattern), provided that you don’t mind visiting them in reverse order (if this is problematic, put them in a list as they’re generated, then walk the list backwards). The trick is similar to that for finding the lowest bit in a number. If we subtract 1 from a subset, then the lowest set element is cleared, and every lower element is set. However, we only want to set those lower elements that are in the superset. So the iteration step is just `i = (i - 1) & superset`

.

```
vector<vector<int>> subsets(vector<int>& nums)
{
vector<vector<int>> vv;
int size = nums.size();
if(size == 0) return vv;
int num = 1 << size;
vv.resize(num);
for(int i = 0; i < num; ++i)
{
for(int j = 0; j < size; ++j)
if((1<<j) & i) vv[i].push_back(nums[j]);
}
return vv;
}
```

Actually there are two more methods to handle this recursion and iteration.

A bitset stores bits (elements with only two possible values: 0 or 1, true or false, ...).

The class emulates an array of bool elements, but optimized for space allocation: generally, each element occupies only one bit (which, on most systems, is eight times less than the smallest elemental type: char).

```
// bitset::count
#include <iostream> // std::cout
#include <string> // std::string
#include <bitset> // std::bitset
int main ()
{
std::bitset<8> foo (std::string("10110011"));
std::cout << foo << " has ";
std::cout << foo.count() << " ones and ";
std::cout << (foo.size()-foo.count()) << " zeros.\n";
return 0;
}
```

Always welcome new ideas and `practical`

tricks! Leave them in the comments!

```
string Manacher(string s) {
//start use $ char
string t = "$#";
for (int i = 0; i < s.size(); i++) {
t += s[i];
t += "#";
}
vector<int> p(t.size(), 0);
int mx = 0, id = 0, resLen = 0, resCenter = 0;
for (int i = 1; i < t.size(); i++) {
p[i] = mx > i ? min(p[2*id - i], mx - i) : 1;
while (t[i + p[i]] == t[i-p[i]]) ++p[i];
if (mx < i + p[i]) {
mx = i + p[i];
id = i;
}
if (resLen < p[i]) {
resLen = p[i];
resCenter = i;
}
}
return s.substr((resCenter - resLen) / 2, resLen - 1);
}
```

**Let us quickly check all the 9 palindrome problem set in leetcode :**

```
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) div *= 10;
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
};
```

Palindrome String Check

We need to skip all the invalid chars !

```
class Solution {
public:
bool isPalindrome(string s) {
int len=s.size();
if(len<=1) return true;
int left=0, right=len-1;
while(left<right){
while(left<right && !check(s[left])) left++;
while(right>left && !check(s[right])) right--;
// if(left==len || right==-1) return true;
if(toupper(s[left])!=toupper(s[right])) return false;
left++;
right--;
}
return true;
}
bool check(char c){
return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9');
}
};
```

```
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> curPath;
dfs(s,curPath,result);
return result;
}
void dfs(string s, vector<string>& curPath, vector<vector<string>>& result) {
if (s.size() == 0) {
result.push_back(curPath);
return;
} else {
for (int i = 1; i <= s.size(); i ++) {
string curWord = s.substr(0,i);
string nextWord = s.substr(i);
if (isPalindrome(curWord)) {
curPath.push_back(curWord);
dfs(nextWord, curPath, result);
curPath.pop_back();
}
}
}
}
bool isPalindrome(string s) {
int start = 0, end = s.size() - 1;
while (start < end) {
if (s[start] == s[end]) {
start ++;
end --;
} else {
return false;
}
}
return true;
}
};
```

Palindrome Partitioning 2

**This problem is the most interesting maybe, we need to check it for many times**

```
class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<vector<bool>> isPalindrome(n, vector<bool>(n, false));
vector<int> dp(n, n);
for(int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (s[i] == s[j] && (i - j < 2 || isPalindrome[j + 1][i - 1])) {
isPalindrome[j][i] = true;
//case : j == 0
if (isPalindrome[0][i]) dp[i] = 0;
else {
dp[i] = min(dp[i], dp[j - 1] + 1);
}
}
}
}
return dp[n - 1];
}
};
```

reverse palindrome linked list

Check whether the linked list is palindrome, just reverse the half and check one by one .

```
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) return true;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* slow = dummy, *fast = dummy;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
reverse(slow);
ListNode* s_head = head, *t_head = slow->next;
while (s_head && t_head) {
if(s_head->val == t_head->val) { s_head = s_head->next; t_head = t_head->next; }
else return false;
}
return true;
}
void reverse(ListNode* head) {
ListNode* start = head->next, *cur = start->next;
while (cur) {
start->next = cur->next;
cur->next = head->next;
head->next = cur;
cur = start->next;
}
return;
}
};
```

Construct all the possible Palindrome Pairs

**We need to recheck this problem**

```
class Solution {
public:
vector<vector<int>> palindromePairs(vector<string>& words) {
vector<vector<int>> result;
unordered_map<string, int> dict;
for(int i = 0; i < words.size(); i++) {
dict[words[i]] = i;
}
for(int i = 0; i < words.size(); i++) {
for(int j = 0; j <= words[i].length(); j++) {
//suffix string is palindrome, so we can add at the end of the string
if (is_palindrome(words[i], j, words[i].size() - 1)) {
string suffix = words[i].substr(0, j);
reverse(suffix.begin(), suffix.end());
if (dict.find(suffix) != dict.end() && i != dict[suffix]) {
result.push_back({i, dict[suffix]});
}
}
if(j > 0 && is_palindrome(words[i], 0, j - 1)) {
string prefix = words[i].substr(j);
reverse(prefix.begin(), prefix.end());
if (dict.find(prefix) != dict.end() && dict[prefix] != i) {
result.push_back({dict[prefix], i});
}
}
}
}
return result;
}
bool is_palindrome(string& s, int start, int end) {
while (start < end) {
if (s[start++] != s[end--]) {
return false;
}
}
return true;
}
};
```

```
class Solution {
public:
bool canPermutePalindrome(string s) {
set<char> t;
for (auto a : s) {
if (t.find(a) == t.end()) t.insert(a);
else t.erase(a);
}
return t.empty() || t.size() == 1;
}
};
class Solution {
public:
bool canPermutePalindrome(string s) {
bitset<256> b;
for (auto a : s) {
b.flip(a);
}
return b.count() < 2;
}
};
```

```
class Solution {
public:
vector<string> generatePalindromes(string s) {
vector<string> res;
unordered_map<char, int> m;
string t = "", mid = "";
for (auto a : s) ++m[a];
for (auto it : m) {
if (it.second & 1) mid += it.first;
t += string(it.second / 2, it.first);
if (mid.size() > 1) return {};
}
permute(t, 0, mid, res);
return res;
}
void permute(string &t, int start, string mid, vector<string> &res) {
if (start >= t.size()) {
res.push_back(t + mid + string(t.rbegin(), t.rend()));
}
for (int i = start; i < t.size(); ++i) {
if (i != start && t[i] == t[start]) continue;
swap(t[i], t[start]);
permute(t, start + 1, mid, res);
swap(t[i], t[start]);
}
}
};
```

]]>There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.

Could you please decide the first play will win or lose?

```
class Solution {
public:
/**
* @param n: an integer
* @return: a boolean which equals to true if the first player will win
*/
bool firstWillWin(int n) {
if(n == 0) return false;
vector<bool> dp(n + 1, false);
// dp[i] = true, the i th coin is fetched by player i
// dp[i] = false, the i th coin is fetched by player i
dp[0] = false;
dp[1] = true;
for(int i = 2; i <= n; i++) {
dp[i] = (!dp[i-2] || !dp[i-1]);
}
return dp[n];
}
};
```

**Coins in a line 2**

There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.

Could you please decide the first player will win or lose?

```
class Solution {
public:
/**
* @param values: a vector of integers
* @return: a boolean which equals to true if the first player will win
*/
bool firstWillWin(vector<int> &values) {
// write your code here
/**
*
* dp[i][j] = max(values[i] + sums[i+1][j] - dp[i+1][j],
* values[i] + values[i+1] + sum[i+2][j] - dp[i+2][j])
*
* <=======>
*
* dp[i][j] = sums[i][j] - min(dp[i+1][j], dp[i+2][j]);
*
**/
int size_ = values.size();
vector<vector<int>> dp(size_, vector<int>(size_, 0));
vector<vector<int>> sums(size_, vector<int>(size_, 0));
for(int i = 0; i < size_; i++) {
for(int j = i; j < size_; j++) {
if(i == j) sums[i][j] = values[i];
else {
sums[i][j] = sums[i][j-1] + values[j];
}
}
}
for (int i = size_ - 1; i >= 0; i--) {
for (int j = i; j < size_; j++) {
if(i == j) {
dp[i][j] = sums[i][j];
}
else if(i + 1 == j) {
dp[i][j] = max(values[i], values[j]);
}
else {
dp[i][j] = sums[i][j] - min(dp[i+1][j], dp[i+2][j]);
// if(i + 2 < size_)
// dp[i][j] = sums[i][j] - min(dp[i+1][j], dp[i+2][j]);
// else {
// dp[i][j] = max(values[i], values[j]);
// }
}
}
}
return dp[0][size_-1] > sums[0][size_-1] - dp[0][size_-1];
}
};
```

**Coins in a line 3**

There are n coins in a line. Two players take turns to take a coin from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.+

Could you please decide the first player will win or lose?

dp题，主要是要推导出公式：

dp[i][j]=max(A[i]+sum[i+1][j]-dp[i+1][j], A[j]+sum[i][j-1]-dp[i][j-1])

A[i]+sum[i+1][j] 和 A[j]+sum[i][j-1]都等于sum[i][j],因此最后公式成为：

dp[i][j]=sum[i][j]-min(dp[i+1][j],dp[i][j-1])

比较特别的dp题。game theory。

```
class Solution {
bool first_win(vector<int> values) {
int size = static_cast<int>(values.size());
if (size <= 1) return true;
int store[size][size];
int sum[size][size];
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
sum[i][j] = i == j ? values[j] : sum[i][j-1] + values[j];
}
}
for (int i = size - 1; i >= 0; i--) {
for (int j = i; j < size; j++) {
if (i == j) store[i][j] = values[i];
else {
int cur = min(store[i+1][j], store[i][j-1]);
store[i][j] = store[i][j] - cur;
}
}
}
return store[0][size-1] > sum[0][size-1] - store[0][size-1];
}
};
```

]]>Or are you talking about somewhere else? In that case, add the link please :-)

]]>I'm a year long leetcode user. This is a fantastic site for programming practice. But I hope that the feature that I wrote in the title could be considered.

Since there are always some fancy solutions posted by those fabulous brains, reading solutions is sort of a thing that I must do for each question. But sometimes the code is pretty much hard to analysis its time and space complexity, which makes me feel very puzzled and upset. So I hope that for each posted solution, there could be an edit box to show those complexities and the analysis with them. It should be able to be edited by not only the writer but also every member of the community who wants to add more specific comments or to make some corrections. This is less time consuming for the following readers and will somehow benefit the interviewees.

Thanks in advance.

Best

]]>I wonder myself why it's not possible to use any library for instance *sortedcontainers* in Python?

Regards

]]>