Monday, July 25, 2016

Pascal's triangle - facebook code lab

July 25, 2016

Given numRows, generate the first numRows of Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Given numRows = 5,
Return
[
     [1],
     [1,1],
     [1,2,1],
     [1,3,3,1],
     [1,4,6,4,1]
]
Plan to work on the problem.

Blogs to read:

1. http://cenalulu.github.io/linux/all-about-cpu-cache/

2. http://cenalulu.github.io/mysql/how-i-become-a-facebook-dba/

3. http://cenalulu.github.io/python/online-programming-test/

4. http://cenalulu.github.io/python/euler-project-experience/

substring - facebook code lab - Leetcode 30

July 25, 2016

You are given a string, S, and a list of words, L, that are all of the same length.
Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
Example :
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).

Plan to work on the problem

Get Java, C++ code:

1. C++ solution: 
study C++ code:
https://gist.github.com/jianminchen/1eb3d40f6173f07c7db90d39c1c71edf

from blog:
https://yujia.io/blog/2015/11/17/LeetCode-30-Substring-with-Concatenation-of-All-Words/

2. sliding windows method - introduction - great idea - ... 
study Java code:
https://gist.github.com/jianminchen/c1f4d4f0b53cd197e3cfaa968a76f62e

from the blog:  http://yuanhsh.iteye.com/blog/2187543

Review sliding window blog:
http://juliachencoding.blogspot.ca/2015/07/leetcode-longest-substring-without.html

Longest common prefix - LCP - facebook code lab

July 25, 2016

Write a function to find the longest common prefix string amongst an array of strings.
Longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2.
As an example, longest common prefix of "abcdefgh" and "abcefgh" is "abc".
Given the array of strings, you need to find the longest S which is the prefix of ALL the strings in the array.
Example:
Given the array as:
[

  "abcdefgh",

  "aefghijk",

  "abcefgh"
]
The answer would be “a”.

Plan to work on the problem

Blog reading:

1. Talk about CMU computer science - network security course in 2015 - good to know the college - computing teaching
http://article.heron.me/2015/05/cmu-nctu-final.html

course project:
https://github.com/heronyang/youtube_fake_view/blob/master/doc/paper.pdf

2. Four algorithm questions to review
http://codechen.blogspot.ca/search/label/interview

Inspired by the above blog, write code for binary tree path sum - two with same value checking:
https://gist.github.com/jianminchen/b5aa95fb574fcb6f4135f88a4b47d5f8

checklist of code style and design issues:
https://gist.github.com/jianminchen/b5aa95fb574fcb6f4135f88a4b47d5f8
2.1. if statement is minimum - avoid using if statement, tips: let it fall through base case.
2.2. code style:
   Readable code
   Clean code
2.3. use LINQ to code select clause like SQL statement
2.4. Avoid early return when the duplicate path sum is added.
2.5. Let main function to take care of discussion of two path sum with same value

3. Find k most frequent numbers in the array
Problem:
  // nums = [5, 3, 1, 1, 1, 3, 73, 1]
  // k = 1
  // return [1]
 
  // k = 2
  // return [1, 3]
 
  // k = 3

  // return [1, 3, 5]


First, go through the array once, and keep the count for every distinct value:

We can use LINK to call order by and then get Top k values.


But, in the analysis of the top k values in the array -

http://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/


1. sorting the array   O(nlogn)
2. use selection sort O(nk)
3. use sorting
4. use min heap
5. use max heap
6. use temporary array
7. use order statistics

7A. randomized selection algorithm - a dertministic algorithm that runs in O(n) in the worst case

 http://www.cse.ust.hk/~dekai/271/notes/L05/L05.pdf
1. the idea is to divide n items into n/5 sets (denoting m sets), each contains 5 items. O(n)
2. Find the median of each of the m sets. O(n)
3. Take those m medians and put them in another array.  Use Dselection() to recurisively calculate the median of these medians. Call this x. T(n/5)
4. ...

7B. Use QuickSort partition algorithm to partition around the kth largest number O(n).

7C. Sort the k-1 elements (elements greater than the kth largest element) O(klogk). This step is needed only if sorted output is required.

longest palindrome - facebook code lab

July 25, 2016

Problem statement:

Given a string S, find the longest palindromic substring in S.
Substring of string S:
S[i...j] where 0 <= i <= j < len(S)
Palindrome string:
A string which reads the same backwards. More formally, S is palindrome ifreverse(S) = S.
Incase of conflict, return the substring which occurs first ( with the least starting index ).
Example :
Input : "aaaabaaa"
Output : "aaabaaa"
Plan to work on java coding in short future. 

Hint:
Brute force: 
How many substrings? - start position and end position, O(N^2) variables, and each substring needs one palindrome check, so time complexity is O(N^3). 


Facebook code lab editorial hint: 


A simpler approach, O(N^2) time and O(1) space:

In fact, we could solve it in O(N^2) time without any extra space.

We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2N-1 such centers.

You might be asking why there are 2N-1 but not N centers?

The reason is that the center of a palindrome can be in between two letters.

Such palindromes have even number of letters (such as “abba”) and their center are between the two ‘b’s.

Since expanding a palindrome around its center could take O(N) time, the overall complexity is O(N^2).



highlights: 

1. String - compile error: string, Java String class, not string. Different from C#
2. String.substring(int beginIndex, endIndex), endIndex is exclusive <- understand exclusive meaning here: line 66, line 90
3. Java String [] operator - compiler error, using charAt() function
4 . line 33 - 36 bug removal - use extra boolean update, since line 35 - update maxLength, so line 36 update boolean should not be used. Saved status 
5. Two for loops can be merged into one loop 
6. Design concern, use start pos and end pos, substring has O(n^2), but if only consider the center position of palindrome, only O(n) case.



Blogs to read:


Excellent analysis - brute force O(n^4) -> O(n^3)

Follow up 


January 11, 2017




Build a palindrome - HackerRank world codesprint #5

July 25, 2016

Read the problem statement more than 30 minutes:

Build a palindrome - problem statement is here


Try to come out the idea to solve the problem first. (Advanced problem) - Learning starts from reading the analysis. Prepare for advanced level challenges from HackerRank, one by one.

Read the editorial notes:

editorial notes


Here are a list terms to review:

1. Consider that >= (L+1)/2 characters are present in the first string.
2. string hashing/ a palindromic tree
3. Iterate on each index i of the given string a and consider the longest palindrome starting from i as a part of your solution to find the maximum length possible, L, for string s.
4. Suffix array
5. LCP - largest common prefix array

Required Knowledge: Suffix Array, Palindromic Tree, String Hashing, Implementation

one selected code to study - Just use it as an example to motivate herself to work hard one by one on small topic, and then, one day in the future, build complicated stuff like this challenge. 

C# code to study


Java code to study


C++ code to study


Previous blog about suffix array

Follow up after 6 months


March 26, 2017

Format the style of the blog, clean up web links and make the web links readable.




Balanced forest - HackerRank - world codesprint #5

July 25, 2016

Spent more than 30 minutes to read the problem statement:

https://www.hackerrank.com/contests/world-codesprint-5/challenges/balanced-forest

Try to come out the idea to solve the problem.

Will come back later.


HackerRank - world codesprint #5 Longest increasing subsequence arrays

July 25, 2016

Problem website:
https://www.hackerrank.com/contests/world-codesprint-5/challenges/longest-increasing-subsequence-arrays

Analysis from editorial:
Because we must use numbers from  to fill each array and we must be able to build an -element LIS for each array, we know each number from to  must appear in the array in increasing order.
We can select  positions where  to  will be placed such that  is placed in the first selected position,  is placed in the second position, , and so on. To avoid overcounting, we impose that there is no  before , no  between the position of  and , and so on. Note that after , we are free to place any value  we want.
For each chosen arrangement, how many ways are there to fill the remaining gaps? There are  unfilled cells and there are  values we can use to fill each position (except the segment from , which can accommodate until ). If we let , we can place .
If we loop over the values of  from  to , then:
Note that after we place the values in the last segment of length , we're left with an array of length  in which the last element must be . That's why we can only choose  integers.
This has a complexity of , provided you precalculate properly.
C# code to study: