Showing posts with label Adobe. Show all posts
Showing posts with label Adobe. Show all posts

Sunday, June 18, 2017

70. Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.



Solution:

This is a Dynamic Programing problem.

We have 1 way to jump to step 1 and 2 ways to jump to step 2.

The ways to jump to step i is the ways to jump to step i - 1 plus the ways to jump to step i - 2.

In other words, from step i - 1, we have only 1 way to jump to step i, which is to jump 1 step.

From step i - 2, we also have only 1 way to jump to step i, which is to jump 2 steps.

Therefore, dp[i] = dp[i - 1] + dp[i - 2].

We can optimize the space by only use two variables to store the states.



Code:


public class Solution {
    public int climbStairs(int n) {
        if (n == 1) {
            return 1;
        }
        if (n == 2) {
            return 2;
        }
        int n1 = 1;
        int n2 = 2;
        for (int i = 3; i <= n; i++) {
            int curr = n1 + n2;
            n1 = n2;
            n2 = curr;
        }
        return n2;
    }
}

Tuesday, June 6, 2017

292. Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.



Solution:

Method 1: Math Formula

Simply write down 1, 2, 3, 4, ... check the sequence and find the law.

1 T
2 T
3 T
4 F
5 T
6 T
7 T
8 F
9 T
....

We find that if n % 4 != 0, the first player can always win.



Code:


public class Solution {
    public boolean canWinNim(int n) {
        return n % 4 != 0;
    }
}



Method 2: Dynamic Programming

This is a more general method.

Given n stones, whether the first player can win depends on whether the second player can win with n - 1, n - 2, or n - 3 stones.


Code:


public class Solution {
    public boolean canWinNim(int n) {
        if (n <= 3) {
            return true;
        }
        boolean[] canWin = new boolean[n + 1];
        canWin[1] = true;
        canWin[2] = true;
        canWin[3] = true;
        for (int i = 4; i <= n; i++) {
            canWin[i] = !canWin[i - 1] || !canWin[i - 2] || !canWin[i - 3];
        }
        return canWin[n];
    }
}

Wednesday, May 10, 2017

258. Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?



Solution:

Let's list a bunch of numbers and the results:

0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
10  1
11  2
12  3
13  4
14  5
15  6
16  7
17  8
18  9
19  1
20  2
21  3
22  4
...   ...

The results are looping from 1 to 9, except the first 0.

So the rules can be:

1. If the number is 0, the result is 0.

2. If the number mod 9 is 0, the result is 9.

3. Otherwise, the result is number mod 9.

Actually, this is called Congruence formula: (n - 1) % 9 + 1



Code:


public class Solution {
    public int addDigits(int num) {
        return (n - 1) % 9 + 1;
    }
}

Monday, May 8, 2017

4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]

The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5



Solution:

If the total length of two sorted arrays is odd. the median is one number from the array. Otherwise, the median is the average of two numbers from the arrays.

We are actually trying to find the kth smallest number in two sorted arrays.

To find it, we check the (k / 2)-th smallest number (let's say valueA )in array A and (k / 2)-th smallest number (let's say valueB) in array B.

If valueA < valueB, we know we can safely remove all the numbers in array A which are smaller than valueA (including valueA itself). And reduce the problem to find (k - k / 2)-th smallest number in two sorted arrays.

If valueB > valueA, we know we can safely remove all the numbers in array B which are smaller than valueB (including valueB itself).

If we find either the remaining array A or B's length is smaller than k / 2, we know we cannot remove element in it. Thus we remove k / 2 elements from the other array.

The time complexity is O(log(m + n)).



Code:


public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len = nums1.length + nums2.length;
        if (len % 2 == 0) {
            return (findKthElement(nums1, 0, nums2, 0, len / 2) + findKthElement(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0;
        }
        return findKthElement(nums1, 0, nums2, 0, len / 2 + 1);
    }
    
    public int findKthElement(int[] A, int startA, int[] B, int startB, int k) {
        if (startA >= A.length) {
            return B[startB + k - 1];
        }
        if (startB >= B.length) {
            return A[startA + k - 1];
        }
        if (k == 1) {
            return Math.min(A[startA], B[startB]);
        }
        
        int valueInA = startA + k / 2 - 1 < A.length ? A[startA + k / 2 - 1] : Integer.MAX_VALUE;
        int valueInB = startB + k / 2 - 1 < B.length ? B[startB + k / 2 - 1] : Integer.MAX_VALUE;
        
        if (valueInA < valueInB) {
            return findKthElement(A, startA + k / 2, B, startB, k - k / 2);
        }
        return findKthElement(A, startA, B, startB + k / 2, k - k / 2);
    }
}

Sunday, May 7, 2017

15. 3Sum

Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],

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



Solution:

For any number x in the input array, we are actually trying to find two other numbers with the sum of -x.

So this problem becomes for each number, find the two sum of its negative.

We first sort the array and then use two pointers to find the two sum.

Notice that we have to do extra work to deal with duplicate numbers.

The time complexity is O(n2).



Code:


public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length < 3) {
            return result;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int target = -nums[i];
            twoSum(nums, target, i + 1, result);
        }
        return result;
    }
    
    public void twoSum(int[] nums, int target, int i, List<List<Integer>> result) {
        int left = i;
        int right = nums.length - 1;
        while (left < right) {
            if (nums[left] + nums[right] == target) {
                List<Integer> list = new ArrayList<>();
                list.add(-target);
                list.add(nums[left]);
                list.add(nums[right]);
                result.add(list);
                left++;
                right--;
                while (left < right && nums[left] == nums[left - 1]) {
                    left++;
                }
                while (right > left && nums[right] == nums[right + 1]) {
                    right--;
                }
            }
            else if (nums[left] + nums[right] < target) {
                left++;
            }
            else {
                right--;
            }
        }
    }
}

Friday, May 5, 2017

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.



Solution:

We keep two pointers i and j and a HashMap to keep track of substring.

The HashMap maintains a character to index map.

We set i to be the start of a substring and j to be the end.

For each j, we check if the character is in the substring by checking the HashMap.

If it has not appeared before, we simply add j + 1 (the next position to this character) to the HashMap. This indicates that if we found a repeat at some point, we need to set i (start of the substring) to skip this character to its next position.

If there is a repeat, we set i to skip the repeated character.



Code:


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0;
        for (int i = 0, j = 0; j < s.length(); j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(i, map.get(s.charAt(j)));
            }
            max = Math.max(max, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return max;
    }
}




public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] check = new int[256];
        int max = 0;
        for (int i = 0, j = 0; j < s.length(); j++) {
            i = Math.max(i, check[s.charAt(j)]);
            max = Math.max(max, j - i + 1);
            check[s.charAt(j)] = j + 1;
        }
        return max;
    }
}




public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<>();
        int start = 0;
        int end = 0;
        int max = 0;
        int count = 0;
        while (end < s.length()) {
            char c = s.charAt(end);
            if (!map.containsKey(c)) {
                map.put(c, 1);
            }
            else {
                map.put(c, map.get(c) + 1);
            }
            if (map.get(c) > 1) {
                count++;
            }
            end++;
            while (count > 0) {
                char ch = s.charAt(start);
                if (map.containsKey(ch)) {
                    map.put(ch, map.get(ch) - 1);
                    if (map.get(ch) > 0) {
                        count--;
                    }
                }
                start++;
            }
            max = Math.max(max, end - start);
        }
        return max;
    }
}

Tuesday, May 2, 2017

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4after calling your function.



Solution:

Since we do not know the previous node of the node we want to remove, we set its value to the value of its next node. And remove the next node from the linked list.



Code:


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

Saturday, April 29, 2017

206. Reverse Linked List

Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?


Solution:

Method 1: recursively

The idea is to reverse the list from the second node, and attaches the head to the end.

For example:
1 -> 2 -> 3 -> 4
=> 1, 2 -> 3-> 4
=> 2 -> 3 -> 4 -> 1



Code:


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



Method 2: iteratively

When we check a node, we want to set its next pointer to its previous node.

Therefore we use a prev node to record its previous node when we go through the list.


Code:


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

1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


Solution:

When we see a number nums[i] in the input array, we want to check if target - nums[i] is also in the input array such that the sum of these two is target.


So, when we go through the input array, we maintains a HashMap that records the numbers we have already seen, and their indices. To check if a number is in the HashMap takes constant time.

If we found a match, we can return. Otherwise, we add the current number with its index to the HashMap.

Since we go through the input array only once, the time complexity is O(n).
The space complexity is O(n) because we use HashMap with extra space.



Code:


public class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>01();
        for (int i = 0; i < nums.length; i++) {     
            if (map.containsKey(target - nums[i])) {
                return new int[] {map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[] {-1, -1};
    }
}

2. 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:

In each round, we do:
1. Create a node with the value of the sum of heads of l1 and l2.
2. Move the heads of l1 and l2 to their next.
3. Update carry.
4. Connect the node to the newly created linked list. 


Code:


/**
 * 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 dummy = new ListNode(0);
        ListNode curr = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry == 1) {
            int v1 = 0;
            int v2 = 0;
            if (l1 != null) {
                v1 = l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                v2 = l2.val;
                l2 = l2.next;
            }
            int sum = v1 + v2 + carry;
            carry = sum >= 10 ? 1 : 0;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
        }
        return dummy.next;
    }
}