atoi
which converts a string to an integer.The function first discards as many whitespace characters as necessary until the first nonwhitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of nonwhitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ‘ ‘ is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.
Example 1:

This challenge is not easy, there are many corner cases in test cases. We need to handle two categories of tests:
My first version of CPP is complicated, I use long long
to handle overflow issue:


This challenge involves complex string processing for parsing. It’s errorprone if we write it by hand.
Therefore, in order to analyze the processing of each input character in an organized way, we can use the concept of finitestate machine.
Our program has a state s
at each moment, and each time a character c
is entered from the sequence, it is transferred to the next state s'
according to the character c
. In this way, we only need to build a table covering all cases of mapping from s
and c
to s'
.
We can also represent the finitestate machine as a table:
state\char  space  +/  digits  other 

start  start  signed  number  wrong 
signed  wrong  wrong  number  wrong 
number  wrong  wrong  number  wrong 
wrong  wrong  wrong  wrong  wrong 
With this table we can easily implement the whole program, the initial state is start
and we change the state according to current character:


Given n, calculate F(n).
Example 1:

Fibonacci numbers is a wellknown mathematical concept, which we also call the Fibonacci sequence. The Fibonacci sequence is closely related to the golden ratio and this is a great video to explain it:
Fibonacci numbers
is defined in recursive paradigm, it’s can be implemented easily in a oneline recursive function.

The computation process is:
But this algorithm is worst in time complexity:
Time complexity is O(2^N), space complexity is O(N).
To remove the duplicated computation, we can add memoization for the recursive function.

If we use a bottomtop computation style, we could get this iterative solution.

The function is constantly increasing, i.e.:

The function interface is defined like this:

For custom testing purposes you’re given an integer function_id and a target z as input, where function_id represent one function from an secret internal list, on the examples you’ll know only two functions from the list.
You may return the solutions in any order.
Example 1:

Explanation: function_id = 1 means that f(x, y) = x + y
Enumerate all the pairs of x
and y
, add the pair into final answer if the result is ‘z’.

Notice the precondition: The function is constantly increasing:

We can set x
to 1 and y
to 1000, this is the middle of all possible results, then we adjust x
and y
according to the result.
This solution is an algorithm of binarysearch.

A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, “abc” is a subsequence of “aebdc” because you can delete the underlined characters in “aebdc” to get “abc”. Other subsequences of “aebdc” include “aebdc”, “aeb”, and “” (empty string).
An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.
Return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence doesn’t exist, return 1.
Example 1:

Iterate all the substring in two strings, try to check weather a substring exists in another string.
Time complexity: O(N^3).

There are several scenarios:
So we can get a oneline solution:

Return true if it is possible to form the array arr from pieces. Otherwise, return false.
Example 1:

Example 2:

Explanation: Concatenate [15] then [88]
Note all the integers in arr
and pieces
are distinct, so we use a ordered_map
to store the relationships between first element and index.
Then iterate all elements in arr
to check whether each element is same with arrays in pieces
.
Time complexity: O(N), where N
is the size of arr
.


Control
and Caps Lock
with my keyboard. I began to do so because I need to use Emacs , and Control
is the most used key in many key bindings in Emacs. I started to experienced Repeated Strain Injury after several years of working, swap these two keys saved me.Not only in Emacs, we actually use Control
much much more than Caps Lock
, but Caps Lock
is usually put in a better position in most keyboard layouts. This standard keyboard layout began almost at 1984, when IBM PC keyboard introduced Model F (PC/AT).
HHKB is an alternative if you want a keyboard with a default layout that prefers to programmers. If you are a Vim/Emacs user, buy one for yourself!
It’s also easy if you want to swap these two keys.
The easiest way is installing PowerToys, and config it in Keyboard Manager:
Remember to keep PowerToys
run in administrator mode.
There are some other ways such as using regedit
to modify, but I haven’t tried it.
Go to Apple Menu > System Preferences… > Keyboard > Keyboard Tab > Modifier Keys and select Control
for Caps Lock
.
When running XWindows you need to modify the X11 key map using xmodmap. It is not sufficient to just modify the console keyboard mapping. Use xmodmap to load the following keymap file (save in ~/.Xmodmap):

These keyboard settings are not persistent after a reboot. Most Linuxes will load your ~/.Xmodmap file when you log in with xdm or gdm. Some don’t. If not then you should add this line to your ~/.xsession and ~/.xinitrc files (after the shebang #!/bin/sh line):

If you are using GNOME, try to install Gnome Tweak Tool:

For version 3.30.0 and later:
For older versions:
Enjoy your new Control
!
iven a string containing digits from 29 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:

We build a map from digits to chars, and enumerate all combinations with chars. This is an classic backtracking algorithm.


binary search
as an introduction example to show the importance of algorithms and details in programming.Binary Search is one of the most famous algorithms in computer science. It’s adopted as a core algorithm in software foundation.
We use binary search
to find a target value in a sorted array. The worst and average time complexity are both O(logN), it’s a classic logN
algorithm.
The core idea in binary search is we always reduce the search space into half compared previous iteration.
Think about how we play the guessnumber
game?
This general algorithm paradigm is called ‘divide and conquer’
Even if the core idea is simple, many programmers do not know how to implement an errorfree binary search.
Although the basic idea of binary search is comparatively straightforward, the details can be surprisingly tricky
— Donald Knuth
Binary search is a typical recursive algorithm, so we can implement it as a recursive function with l
as left range and r
as the right range.
We need to calculate the mid
index, then update left range and right range according to the compare results between nums[mid]
and target.

The terminate condition is l > r
, which means the search space is zero. Based on recursive version, we can safely convert it into an imperative function:

Why binary search is not easy to implement bugfree?
There are two tricky points here:
The first is terminate condition, if someone wrote the testing expression as l < r
, target value will be missed in some scenarios.
Another issue that is easy to overlook is programming language depended, in any language with integer
in a fixed range, inappropriate method to compute midindex may introduce overflow error.
int m = l + ((r  l) >> 1);
is same semantic meaning int m = (l + r) / 2
, but l+r
will overflow for large numbers.
When there are duplicated values in an array, what the result will be returned? You can write some sample arrays as input.
For the above naive implementation, we will get anyone from the continuous index of the target.
But how we could get the first or last positions of a target?
We could still use divide and conquer method but with trivial detail.
Suppose we want to get the first position, whenever we find a index with target value, we drop the right part and continue to search with left part. But we need an extra index to store current position:

Similarly, to get the last position we only need to update l
to mid+1
.
Try to write a binarysearch in your favorite programming language and think about how to write unit testing for it.
And here are my more tips on learning data structures and algorithms.
]]>Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn’t have “lakes”, meaning the water inside isn’t connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.

Explanation: The perimeter is the 16 yellow stripes in the image above.
This is a typical DFS problem, but we need to store the boundary counts during the searching process.
The perimeter contains edges in two categories:
For convenient , we set the grid value into 2 if we visited a cell, otherwise we need another extra memory to store the visited information.
Time complexity is O(M*N).

If you think about more, we may find out that we don’t need to use DFS or BFS.
We only need to iterate all the cells and calculate the boundary edges (according to the two above categories).
Time complexity is O(M*N).

To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
If k > 0, replace the ith number with the sum of the next k numbers.
If k < 0, replace the ith number with the sum of the previous k numbers.
If k == 0, replace the ith number with 0.
As code is circular, the next element of code[n1] is code[0], and the previous element of code[0] is code[n1].
Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!
Example 1:

Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.
This is an easy challenge, we only need to iterate the array and calculate the previous(or latter) ksum
.
Note for the negative index, we need to add code.size()
and then mod
it into range [0, code.size()1]
.
Time complexity is O(N*k)
