Tuesday, June 6, 2017

LeetCode Questions

My Solutions to Leet Code questions 


Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution :
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
     
        ListNode result, head= new ListNode(0);
        result = head ;
     
        int resultVal =0;
        int carry = 0;
        while(l1 != null || l2 != null || carry !=0){
            resultVal = carry;
         
            if(l1 != null) {
                resultVal += l1.val;
                l1 = l1.next;
            }
         
            if(l2 != null) {
                resultVal += l2.val;
                l2 = l2.next;
            }
         
            carry = 0;
         
            if(resultVal >= 10) {
                carry = resultVal / 10;
                resultVal = resultVal % 10;
            }
         
            ListNode sum = new ListNode(resultVal);
            result.next = sum;
            result = sum;
        }
     
        return head.next;
    }
}

--------------------------------------------------------------------------------------------------------------------------

Serialize and Deserialize Binary Tree


Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree

  1
   / \
  2   3
     / \
    4   5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Solution:

/**
 * Definition for a binary tree node. public class TreeNode { int val; TreeNode
 * left; TreeNode right; TreeNode(int x) { val = x; } }
 */
public class Codec {

// Encodes a tree to a single string.
public String serialize(TreeNode root) {
System.out.println("serialize data: ");
if (root == null)
return "X";
String result = "";
result = traverse(root, result);
System.out.println("resturn serialize data: " + result);
return result;
}
private String traverse(TreeNode node, String result) {
if (node == null) {
result += ",X";
return result;
} else {
result += (result.isEmpty() ? node.val : "," + node.val);
}
result = traverse(node.left, result);
result = traverse(node.right, result);
return result;
}

// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
System.out.println("deserialize : " + data);
if (data == null || data.equals("X")) {
return null;
}
String[] nodeStr = data.split(",");
Queue<String> queue = new LinkedList<String>();
for (int i = 0; i < nodeStr.length; i++) {
queue.add(nodeStr[i]);
}
System.out.println("nodeStr length : " + nodeStr.length);
TreeNode root = null;
root = insert(root, queue);
return root;
}
public TreeNode insert(TreeNode node, final Queue<String> queue) {
// System.out.println("Current Queue Size : " + queue.size());
if (queue.peek().equals("X")) {
queue.remove();
return null;
}
// System.out.println("Added node : " + queue.peek());
node = new TreeNode(Integer.parseInt(queue.remove()));
node.left = insert(node, queue);
node.right = insert(node, queue);
return node;
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

PS :: Its better to use String builder while serializing.
--------------------------------------------------------------------------------------------------------------------------

Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

Solution :


public class Solution {
     public ArrayList<Integer> findAnagrams(String haystack, String needle) {

Integer[] result = null;
int[] needleChars = new int[26];

for (int i = 0; i < needle.length(); i++) {
needleChars[needle.charAt(i) - 'a']++;
}

ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i <= haystack.length() - needle.length(); i++) {
boolean isAnagram = checkAnagram(haystack.substring(i, i + needle.length()), needleChars);
if (isAnagram) {
list.add(i);
}
}
return list;
}

private boolean checkAnagram(String anagramStr, int[] needleChars) {
    int[] charArr = Arrays.copyOf(needleChars, needleChars.length);
    for(int i=0; i< anagramStr.length(); i++){  
    needleChars[anagramStr.charAt(i) - 'a']);
    if(charArr[anagramStr.charAt(i) - 'a'] >= 1){   
    charArr[anagramStr.charAt(i) - 'a']--;    
    } else {
    return false;
    }
    }
    
return true;
}
}

---------------------------------------------------------------------------------------------------------------------

Find all unique triplets in the array which gives the sum of zero

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

No comments:

Post a Comment