2012年1月15日星期日

Implement atoi


Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Requirements for atoi:
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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


Used Java because it`s cleaner

public int atoi(String str) {
        // Start typing your Java solution below
        // DO NOT write main() function
        String expression = str.trim();
        if(expression==null||expression.equals("")){
            return 0;
        }
        int sign = 1;
        int index = 0;
        if(expression.charAt(0) == '-'){
            sign = -1;
        }
        if(expression.charAt(0) == '-' || expression.charAt(0) == '+'){
            index++;
            if(expression.length()==1){
                return 0;
            }
        }
        int ret = 0;
        while(index < expression.length()){
            char c = expression.charAt(index);
            if(c < '0' || c > '9') break;
            int value = c - '0';
            if(sign > 0){
                if(ret > Integer.MAX_VALUE / 10) return Integer.MAX_VALUE;
            }else{
                if(ret < Integer.MIN_VALUE / 10) return Integer.MIN_VALUE;
            }
            ret = ret*10;
            if(sign > 0){
                if(ret > Integer.MAX_VALUE - value)  return Integer.MAX_VALUE;
            }else{
                if(ret < Integer.MIN_VALUE + value ) return Integer.MIN_VALUE;
            }
            ret += value * sign;          
            index++;
        }
        return ret;
    }

2012年1月14日星期六

Palindrome Number


Determine whether an integer is a palindrome. Do this without extra space.
Some hints: Could negative integers be palindromes? (ie, -1)


If you are thinking of converting the integer to string, note the restriction of using extra space.


You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?


There is a more generic way of solving this problem.



    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int numOfDigits = 1;
        int base = 1;
        while(x / base > 9) {
            base *= 10;
            ++numOfDigits;
        }
     
        int head, tail;
        for(int i = 0; i < numOfDigits / 2; ++i) {
            head = x / base;
            tail = x % 10;
            if(head != tail) return false;
            x -= head * base;
            x /= 10;
            base /= 100;
        }
        return true;
    }

2012年1月12日星期四

In-place array rotation


The idea that is commonly seen in skill testing interview questions is using three reversals to perform the rotations: rev(1,k) rev(k+1,n-k) rev(1,n). This leads us to the following code:

int reverse(struct baseType * a, int n) 
    int i, j; 
    j = n / 2;
    n--;
    for (i=0; i < j; i++) 
        struct baseType tmp = a[i]; 
        a[i] = a[n-i];
        a[n-i] = tmp;
    }
    return 0;
}

int rotate(struct baseType a[], int n, int k) 
    if(a == NULL || n <= 0) 
       return -__LINE__;
    if(k < 0 || k >= n)
       k %= n; 
       if (k < 0) k += n; 
    }
    if (k == 0) return 0;
    reverse (a, k);
    reverse (a + k, n - k);
    reverse (a, n);
    return 0;
 }


This solution reads and writes each element twice, however, some quick performance testing on random arrays shows that this code is faster for very small sized baseTypes. The reason being that the reverse() is very good for memory access locality. However, for any larger sized baseTypes, the first code sequence given will win by the simple virtue of performing fewer operations.

Rotating a 2D array of integers (matrix) by a given angle (+90, -90, +180, -180)

This is posted by 

So, I came across this problem on a forum and before looking up, I tried to solve it. After 15 minutes of trying, I figured out that the solution is pretty easy and elegant which was messy otherwise if you are going to do it in an insane way. So, here we go:

Problem definition: You are given a 2D square matrix, or 2D array of integers of size n (n rows and n columns), your output should be n by n 2D matrix rotated by a given angle, which could be +90, -90, +180, -180.

Example:
Input                                              Output
1 2 3                                              7 4 1
4 5 6     Rotate by +90                   8 5 2
7 8 9                                              9 6 3

If you go by solving it something like manually, swapping elements, its going to be messy, tedious, and error prone in that there will be much more edge cases, test cases to handle. So, after trying on paper, I figured out following elegant solution to solve this in an easy manner.

Rotate by +90 (clockwise once):

Input: n by n matrix M, where n >= 2
Algorithm:
Step 1: Transpose M
Step 2: Reverse each row

Dry run:
Step 1: Transpose
M                   M'
1 2 3              1 4 7
4 5 6      --     2 5 8
7 8 9              3 6 9

Step 2: Reverse each row
M'                  M''
1 4 7              7 4 1
2 5 8      --     8 5 2
3 6 9              9 6 3

M'' is rotated form of M by +90 degree.

Pseudocode: is here which is self explanatory and easily convertible to source code in a language of your choice.

Transpose
    for i in [0, n)
        for j in [0, n)
            if ( i < j )
                swap( M[i][j], M[j][i] )

Reverse a row (rowidx)
    start = 0
    end = cols - 1
    while ( start < end ) {
        swap( M[rowidx][start], M[rowidx][end] )
        ++start
        --end
    }

Rotate
    Transpose
    for i in [0, rows)
        Reverse( i )

That was fair enough until only asked to rotate by +90 degree. If problem is further extended to be solved for any given angle, of course the rotation should make sense, for example, 47 degree is not a choice ;-). So, here are some elegant techniques (I'll be brief now for other angles, because for +90 degree I have elaborated the solution):

Rotation by -90 degree (anticlockwise once):

Step 1: Transpose
Step 2: Reverse each column

Rotation by +180 degree (clockwise twice): Two methods follows

First:
Rotate input matrix +90 degree twice, if routine for which is available to you

Second: (You'll be amazed!)
Step 1: Reverse each row
Step 2: Reverse each column

Rotation by -180 degree (anticlockwise twice): Three(!!!) methods follows

First:
Rotate input matrix -90 degree twice, if routine for which is available to you

Second: (You'll be amazed again!)
Step 1: Reverse each column
Step 2: Reverse each row

Third: (Aha!)
Because rotating a matrix +180 degree or -180 should produce same result. So you can rotate it by +180 degree using one of above methods.

Concluding note: Above techniques are elegant and very simple and straightforward to implement. Try them for some input of your choice and rotate it in all angles. These techniques are tested with a working C program.