Wednesday, February 7, 2018

[2018-Interview] Reverse Linked List

Original question: https://leetcode.com/problems/reverse-linked-list/description/


My answer:

Iterative and recursive: too slow. Please check out the better solution below.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
           // Solution 1
        // if (head == null || head.next == null) {
        //     return head;
        // }
//         ListNode nextHead = reverseList(head.next);

//         ListNode endNode = nextHead;

//         while (endNode.next != null) {
//             endNode = endNode.next;
//         }
//         head.next = null;
//         endNode.next = head;
//         return nextHead;
        // Solution 2
        if (head == null || head.next == null) {
            return head;
        }
        LinkedList<ListNode> list = new LinkedList<ListNode>();
        ListNode current = head;
        while(current != null) {
            list.addLast(current);
            current = current.next;
        }
        while (!list.isEmpty() && list.size() != 1) {
            ListNode firstNode = list.removeFirst();
            ListNode lastNode = list.removeLast();
            int temp = firstNode.val;
            firstNode.val = lastNode.val;
            lastNode.val = temp;
        }
        return head;
    }
}

Better solution:

1. Iterative: move the next node of HEAD to be the one right after dummy node, until HEAD is the last one


class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head) return head;
        ListNode *dummy = new ListNode(-1);
        dummy->next = head;
        ListNode *cur = head;
        while (cur->next) {
            ListNode *tmp = cur->next;
            cur->next = tmp->next;
            tmp->next = dummy->next;
            dummy->next = tmp;
        }
        return dummy->next;
    }
};

2. Recursive:


class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *p = head;
        head = reverseList(p->next);
        // after above reversing, p->next is already the end node,
        // below steps move p to the end
        p->next->next = p;
        p->next = NULL;
        return head;
    }
};

Monday, February 5, 2018

[2018-Interview] Remove Nth Node From End of List

Original question: https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

My answer:

Have a endNode move forward so that it is n step further than currentNode, then move endNode until last one. The next of currentNode is then the one to be deleted.



/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n < 1 || head == null) {
            return null;
        }
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode prevNode = preHead;
        ListNode currentNode = head;
        ListNode endNode = head;
        int step = 0;
        while (endNode.next != null && step < n) {
            endNode = endNode.next;
            step++;
        }
        if (step < n) {
            return preHead.next.next;
        }
        while (endNode.next != null) {
            currentNode = currentNode.next;
            endNode = endNode.next;
        }
        currentNode.next = currentNode.next.next;
        return preHead.next;
    }
}

[2018-Interview] Delete Node in a Linked List

Original question: https://leetcode.com/problems/delete-node-in-a-linked-list/description/

My answer: too stupid. LOL


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        ListNode currentNode = node;
        ListNode nextNode = node.next;
        ListNode prevNode = null;
        while (nextNode != null) {
            currentNode.val = nextNode.val;
            prevNode = currentNode;
            currentNode = nextNode;
            nextNode = nextNode.next;
        }
        prevNode.next = null;
    }
}

Better solution:


public class Solution {
    /**
     * @param node: the node in the list should be deleted
     * @return: nothing
     */
    public void deleteNode(ListNode node) {
        // write your code here
        if (node == null || node.next == null)
            return;
        ListNode next = node.next;
        node.val = next.val;
        node.next = next.next;
        return;
    }
}

[2018-Interview] Longest Common Prefix

Original question: https://leetcode.com/problems/longest-common-prefix/description/

My answer:


class Solution {
    public String longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        if (strs == null || strs.length <= 0) {
            return sb.toString();
        }
        if (strs.length == 1) {
            return strs[0];
        }
        int i = 0;
        while (i < strs[0].length()) {
            if (isSameForAll(strs, i)) {
                sb.append(strs[0].charAt(i));
                i ++;
            } else {
                break; 
            }
        }
        return sb.toString();
        
    }
    private boolean isSameForAll(String[] strs, int i) {
        for (int j = 1; j < strs.length; j ++) {
            if (i < strs[j].length() ) {                
                if (strs[j].charAt(i) != strs[0].charAt(i)) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }
}

Another solution is to start from the first one, compare prefix with next string, until end



public class Solution {
    
    // 1. Method 1, start from the first one, compare prefix with next string, until end;
    // 2. Method 2, start from the first char, compare it with all string, and then the second char
    // I am using method 1 here
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        for(int i = 1; i < strs.length; i++) {
            int j = 0;
            while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
                j++;
            }
            if( j == 0) {
                return "";
        }
            prefix = prefix.substring(0, j);
        }
        return prefix;
    }

}

Sunday, February 4, 2018

[2018-Interview] Count and Say

Original question: https://leetcode.com/problems/count-and-say/description/

My answer: Recursive solution.




class Solution {
    public String countAndSay(int n) {
        if (n < 1) {
            return "";
        }
        if (n == 1) {
            return "1";
        }
        n --;
        String prevResult = countAndSay(n);
        int count = 1;
        char currentChar = prevResult.charAt(0);
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < prevResult.length(); i ++) {
            if (currentChar == prevResult.charAt(i)) {
                count ++;
            } else {
                sb.append(count + "");
                sb.append(currentChar);
                count = 1;
                currentChar = prevResult.charAt(i);
            }
        }
        sb.append(count + "");
        sb.append(currentChar);
        
        return sb.toString();
    }
}


Thursday, February 1, 2018

[2018-Interview] Implement strStr()

Original question: https://leetcode.com/problems/implement-strstr/description/

My Answer:



class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack != null && needle != null && (haystack.equals(needle) || needle.length() == 0)) {
            return 0;
        }
        if (haystack == null || needle == null || needle.length() > haystack.length() ) {
            return -1;
        }
        // brute force
        int h = 0;
        for (; h < haystack.length() - needle.length() + 1; h ++) {
            int i = 0;
            for (; i < needle.length(); i++) {
                if (haystack.charAt(h + i) != needle.charAt(i)) {
                    break;
                }
            }
            if (i == needle.length()) {
                return h;
            }
        }
        return -1;
    }
}

KMP algorithm should be the best solution, but it is difficult to understand and implement during interview.

KMP Article: http://www.matrix67.com/blog/archives/115