Leetcode: Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [1,3,2].

1. Recursive Version

public ArrayList<Integer> inorderTraversal(TreeNode root) {
    //recursive version
    ArrayList<Integer> result = new ArrayList<>();
    traversalHelper(root, result);
    return result;
}

public void traversalHelper(TreeNode root, ArrayList<Integer> result) {
    if (root == null) {
        return;
    }
    traversalHelper(root.left, result);
    result.add(root.val);
    traversalHelper(root.right, result);
}

2. Non-recursive Version

public ArrayList<Integer> inorderTraversal(TreeNode root) {
    //non-recursive version
    ArrayList<Integer> result = new ArrayList<>();
    Stack<TreeNode> stack = new Stack<>();
    TreeNode curr = root;
    while (curr != null || !stack.empty()) {
        TreeNode left = curr;
        while (left != null) {
            stack.push(left);
            left = left.left;
        }
        curr = stack.pop();
        result.add(curr.val);
        curr = curr.right;
    }
    return result;
}
FacebookTwitterGoogle+Share

Leetcode: Anagrams

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

public ArrayList<String> anagrams(String[] strs) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<String> output = new ArrayList<String>();
        HashMap<String,ArrayList<String>> patterns = new HashMap<String,ArrayList<String>>();

        for(int i=0;i<strs.length;i++){
            char[] charArr = strs[i].toCharArray();
            Arrays.sort(charArr);
            String sorted = new String(charArr);

            if(patterns.containsKey(sorted)){
                patterns.get(sorted).add(strs[i]);
            }else{
                ArrayList<String> newPattern = new ArrayList<String>();
                newPattern.add(strs[i]);
                patterns.put(sorted,newPattern);
            }
        }

        for(String str :patterns.keySet()){
            if(patterns.get(str).size()>1){
                output.addAll(patterns.get(str));
            }
        }
        return output;
    }

Analysis: Time complexity: O(n*mlgm)  (n is # of strings, m is the average length of each string) Space Complexity: O(n*m)

Leetcode: Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // Start typing your Java solution below
        // DO NOT write main() function

        ListNode head = new ListNode(-1);
        ListNode runner = head;

        int carry = 0;
        while(l1!=null || l2!=null){
            int val1 = l1==null?0:l1.val;
            int val2 = l2==null?0:l2.val;
            int sum = val1 + val2 + carry;
            
            if(sum>9){
                sum = sum - 10;
                carry = 1;
            }else{
                carry = 0;
            }
            if(head.val==-1){
                head.val = sum;
            }else{
                ListNode newNode = new ListNode(sum);
                runner.next = newNode;
                runner = runner.next;
            }
            l1 = l1==null?null:l1.next;
            l2 = l2==null?null:l2.next;
        }
        
        if(carry==1){
            ListNode newNode = new ListNode(1);
            runner.next = newNode;            
        }
        return head;
    }
}

 

Leetcode: 3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)
public class Solution {
    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> output = new ArrayList<ArrayList<Integer>>();
        if(num==null||num.length<3){
            return output;
        }
        HashSet<ArrayList<Integer>> pairsFound = new HashSet<ArrayList<Integer>>();
        Arrays.sort(num);
        for(int i=0;i<num.length;i++){
            ArrayList<ArrayList<Integer>> result = twoSum(num, 0-num[i]);
            for(ArrayList<Integer> pair:result){
                if(pair.get(0)!=i && pair.get(1)!=i){
                    int[] temp = new int[3];
                    temp[0] = i;
                    temp[1] = pair.get(0);
                    temp[2] = pair.get(1);
                    Arrays.sort(temp);
                    ArrayList<Integer> newTriple = new ArrayList<Integer>();
                    for(int j=0;j<temp.length;j++){
                        newTriple.add(num[temp[j]]);
                    }
                    if(!pairsFound.contains(newTriple)){
                        pairsFound.add(newTriple);
                        output.add(newTriple);
                    }
                }
            }
        }
        return output;
    }

    public ArrayList<ArrayList<Integer>> twoSum(int[] num, int sum){
        ArrayList<ArrayList<Integer>> output = new ArrayList<ArrayList<Integer>>();
        int i = 0;
        int j = num.length-1;
        while(i<j){
            if(num[i]+num[j]==sum){
                ArrayList<Integer> newPair = new ArrayList<Integer>();
                newPair.add(i);
                newPair.add(j);
                output.add(newPair);
                i++;
                j--;
            }else if(num[i]+num[j]>sum){
                j--;
            }else{
                i++;
            }
        }
        return output;
    }
}