Coder's Cat http://coderscat.com/icon.png Be a Better Programmer 2020-12-29T03:20:02.268Z http://coderscat.com/ Nick Chen Hexo LeetCode: String to Integer (atoi) http://coderscat.com/leetcode-string-to-integer-atoi/ 2020-12-29T10:32:36.000Z 2020-12-29T03:20:02.268Z Implement `atoi` which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace 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 non-whitespace 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 32-bit 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:

## Explanation

This challenge is not easy, there are many corner cases in test cases. We need to handle two categories of tests:

• Overflow or underflow, we need to return INT_MAX or INT_MIN depends on it is signed or not
• Signed or not, and whether it is a valid number

## Solution #1: Brute force

My first version of CPP is complicated, I use `long long` to handle overflow issue:

## Solution #3: Finite-state machine

This challenge involves complex string processing for parsing. It’s error-prone 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 finite-state 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 finite-state machine as a table:

state\charspace+/-digitsother
startstartsignednumberwrong
signedwrongwrongnumberwrong
numberwrongwrongnumberwrong
wrongwrongwrongwrongwrong

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

Preparing for an interview? Check out this!

]]>
<p>Implement <code>atoi</code> which converts a string to an integer.</p> <p>The function first discards as many whitespace characters as
LeetCode: Fibonacci Number http://coderscat.com/leetcode-fibonacci-number/ 2020-12-19T19:00:59.000Z 2020-12-22T03:05:02.750Z The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

Given n, calculate F(n).

Example 1:

## Explanation

Fibonacci numbers is a well-known 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:

## Recursive Solution

`Fibonacci numbers` is defined in recursive paradigm, it’s can be implemented easily in a one-line 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).

## Top-bottom Solution with Memoization

To remove the duplicated computation, we can add memoization for the recursive function.

## Dynamic programming: Iterative Solution

If we use a bottom-top computation style, we could get this iterative solution.

Preparing for an interview? Check out this!

]]>
<p>The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two
LeetCode: Find Positive Integer Solution for a Given Equation http://coderscat.com/leetcode-find-positive-integer-solution-for-a-given-equation/ 2020-12-18T10:00:00.000Z 2020-12-18T10:45:03.763Z Given a function  f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.

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

## Brute force Solution

Enumerate all the pairs of `x` and `y`, add the pair into final answer if the result is ‘z’.

## Binary-search Solution

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 binary-search.

Preparing for an interview? Checkout this!

]]>
<p>Given a function  f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.</p> <p>The function is constantly
LeetCode: Longest Uncommon Subsequence I http://coderscat.com/leetcode-longest-uncommon-subsequence-i/ 2020-12-12T10:00:00.000Z 2020-12-12T00:02:03.075Z Given two strings a and b, find the length of the longest uncommon subsequence between them.

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:

## Brute force solution

Iterate all the substring in two strings, try to check weather a substring exists in another string.

Time complexity: O(N^3).

## Clever solution

There are several scenarios:

• a = b, we will return -1
• a != b, in this case any specific one string is not the substring of another, so we return the string with a longer length.

So we can get a one-line solution:

Preparing for an interview? Checkout this!

]]>
<p>Given two strings a and b, find the length of the longest uncommon subsequence between them.</p> <p>A subsequence of a string s is a
LeetCode: Check Array Formation Through Concatenation http://coderscat.com/leetcode-check-array-formation-through-concatenation/ 2020-12-11T21:58:00.000Z 2020-12-11T11:00:03.229Z You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].

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

Example 1:

Example 2:

Explanation: Concatenate  then 

## CPP solution

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`.

## Java Solution

Preparing for an interview? Checkout this!

]]>
<p>You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your
Swap Caps Lock and Control http://coderscat.com/swap-caps-lock-and-control/ 2020-12-09T12:08:00.000Z 2020-12-10T03:40:04.102Z After almost 15 years of programming life, I always want to swap the `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.

## Windows

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.

## Mac

Go to Apple Menu -> System Preferences… -> Keyboard -> Keyboard Tab -> Modifier Keys and select `Control` for `Caps Lock`.

## Linux

### x11

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):

### make these changes persistent

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):

### Gnome

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

For version 3.30.0 and later:

• Open the tweak-tool and click on the Keyboard & Mouse section in the left menu bar.
• Click on the Additional Layout Options button on the left.
• Under Caps Lock behavior select Caps Lock is also a Ctrl.

For older versions:

• Open the tweak-tool and click on the typing section in the left column.
• You should now see the line Caps Lock key behavior on the left.
• Choose Make CapsLock an additional Ctrl key instead of Disabled in the drop-down list and you should be good.

Enjoy your new `Control`!

]]>
<p>After almost 15 years of programming life, I always want to swap the <code>Control</code> and <code>Caps Lock</code> with my keyboard. I
LeetCode: Letter Combinations of a Phone Number http://coderscat.com/leetcode-letter-combinations-of-a-phone-number/ 2020-12-08T21:58:00.000Z 2020-12-08T07:30:04.918Z Problem

iven a string containing digits from 2-9 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:

## Cpp Solution

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

## Java Solution

Preparing for an interview? Checkout this!

]]>
<h2 id="Problem"><a href="#Problem" class="headerlink" title="Problem"></a>Problem</h2><p>iven a string containing digits from 2-9
Binary Search http://coderscat.com/binary-search/ 2020-12-03T16:30:00.000Z 2020-12-22T03:15:02.820Z When teaching programming to beginners, I always like to use `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.

## Divide and conquer

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 `guess-number` 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 error-free 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 bug-free?

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 mid-index 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.

## Duplicated values

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`.

## Conclusion

Try to write a binary-search 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.

]]>
<p>When teaching programming to beginners, I always like to use <code>binary search</code> as an introduction example to show the
LeetCode: Island Perimeter http://coderscat.com/leetcode-island-perimeter/ 2020-12-03T10:43:00.000Z 2020-12-03T02:00:04.830Z You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.

Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

The island doesn’t have “lakes”, 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.

## Depth first search(DFS) with count

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:

1. The water cell adjacent to a land cell
2. The land cell’s edges located at the border of map

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).

## Bruce-Force

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).

]]>
<p>You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.</p> <p>Grid
LeetCode: Defuse the Bomb http://coderscat.com/leetcode-defuse-the-bomb/ 2020-12-02T14:43:00.000Z 2020-12-02T02:35:02.254Z You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.

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[n-1] is code, and the previous element of code is code[n-1].

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.

## Solution

This is an easy challenge, we only need to iterate the array and calculate the previous(or latter) `k-sum`.
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)

]]>
<p>You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a