Iterator Interface

Binary Search Tree Iterator

https://leetcode.com/problems/binary-search-tree-iterator/

public class BSTIterator {
    Stack<TreeNode> st=new Stack<TreeNode>();
    TreeNode cur=null;
    
    public BSTIterator(TreeNode root) {
        cur=root;
        while(cur!=null){ 
                st.push(cur);
                cur=cur.left; 
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !st.empty();
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode tmp=st.pop(); 
        cur=tmp;
        if (cur.right!=null){
               cur=cur.right;
               while(cur!=null){
                   st.push(cur);
                   cur=cur.left;
               }
        } 
        return tmp.val;   
    }
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */

Peeking Iterator
https://leetcode.com/problems/peeking-iterator/

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
    private Iterator<Integer> it;
    boolean flag=false;
    Integer nextElement=null;
	public PeekingIterator(Iterator<Integer> iterator) {
	    // initialize any member here.
	    this.it=iterator;
	}

    // Returns the next element in the iteration without advancing the iterator.
	public Integer peek() {
	     if (!flag){
	         nextElement=it.next();
	         flag=true; 
	     } 
	     return nextElement;
	     
	}

	// hasNext() and next() should behave the same as in the Iterator interface.
	// Override them if needed.
	@Override
	public Integer next() {
	     if (flag){
	         flag=false;
	         Integer res=nextElement;
	         nextElement=null;
	         return res;
	     }else{
	         
	         return it.next();
	     }
	}

	@Override
	public boolean hasNext() {
	    return flag||it.hasNext();
	}
}

Zigzag Iterator

Given two 1d vectors, implement an iterator to return their elements alternately.
For example, given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
Clarification for the follow up question – Update (2015-09-18):
The “Zigzag” order is not clearly defined and is ambiguous for k > 2 cases. If “Zigzag” does not look right to you, replace “Zigzag” with “Cyclic”. For example, given the following input:
[1,2,3]
[4,5,6,7]
[8,9]
It should return [1,4,8,2,5,9,3,6,7].
[思路]
iterator都放到一个list里, 用一个count循环,

public class zigZagIterator {
	private List<Iterator<Integer>> list=new ArrayList<Iterator<Integer>>();
	int count=0;
	
	public zigZagIterator(Iterator<Integer> v1, Iterator<Integer> v2) {  
		list.add(v1);
		list.add(v2);
	}
	
	public int next(){
		int ret=list.get(count).next();
		if (!list.get(count).hasNext()) list.remove(count);
		else count++;
		if (list.size()>0) count%=list.size();
		return ret;
	}
	public boolean hasNext(){
		return !list.isEmpty();
	}
}
Iterator Interface

House Robber I && II – dp

House Robber I
public class Solution {
public int rob(int[] nums) {
if (nums.length==0) return 0;

int last1=0;
int last2=nums[0];
for(int i=1;i<nums.length;i++){
int temp=Math.max(last1+nums[i],last2);
last1=last2;
last2=temp;
}

return last2;
}
}
House Robber II
public class Solution {
public int rob(int[] nums) {
if (nums.length==0) return 0;
if (nums.length==1) return nums[0];
int[] dp=new int[nums.length];
//include 1st one, not last one
dp[0]=nums[0];
dp[1]=nums[0];
for(int i=2;i<nums.length-1;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
}
int max1=dp[nums.length-2];
//include last one, not include the first one
dp[0]=0;
dp[1]=nums[1];
for(int i=2;i<nums.length;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
}
return Math.max(max1,dp[nums.length-1]);
}
}

House Robber I && II – dp

如果实现像 facebook 一样的 activity broadcast

如果实现像 facebook 一样的 activity broadcast.
一个朋友 f1 更新一条信息后,他的所有朋友都要看到这条信息。
条件:
1. 朋友数量极大。
2. 有的朋友在线,有的不在线,不在线的登陆后要能看到。
3. 如果储存空间有限,如何处理。

先讨论fan-out和pull两种模式的优劣,比如前者没有availability问题,但是需要大
量随机disk seek操作,朋友数极大可能会产生backlog,就需要考虑各种write优化的
DB,比如Cassandra或者HBase等。后者没有大量随机disk seek问题,但是有
availability问题。

FB在其news feeds中采用的pull模式,找找相关视频、slides过一遍就懂了,看看
services怎么划分,采用了几个模块,节约空间,其中一些交互是用id。

储存空间有限?先问问面试官怎么约束?是内存有限还是硬盘有限?是单机有限还是整
个DC有限。
http://www.tuicool.com/articles/BJRJja
Facebook起源的NewsFeed,以及Twitter起源的Timeline,核心问题都是如何处理巨大的消息(活动,activity)分发。“推Push”和“拉Pull”或者“推拉结合”,是主要的处理方式。

各大网站都大量使用的Nginx, memcached, MySQL等开源产品,都标配了,文中不再提。实现技术上,异步消息队列的引入,来模块解耦和尖峰削平;Cache的精良设计等,也都是各家大量使用的技能,可看参看文档,不再详述。
推 Push, fan-out, Write-fanout 写时消息推送给粉丝。空间换时间
拉 Pull, fan-in, Read-fanout 读时拉取所有好友的消息,再聚合。时间换空间
混合 Hybrid 基于推,混入拉;基于拉,加速推。时空平衡

参考:http://mitbbs.org/article_t1/JobHunting/32893463_32893905_1.html

如果实现像 facebook 一样的 activity broadcast

Repeated DNA Sequence

public class repeatedDNASequence {
public List findRepeatedDnaSequences(String s) {
List res=new ArrayList();
if (s.length()<10) return res;
HashMap map=new HashMap();
HashMap dict=new HashMap();
dict.put(‘A’, 0);
dict.put(‘C’, 1); dict.put(‘G’, 2); dict.put(‘T’, 3);
for(int i=0;i<s.length()-9;i++){
String tmp=s.substring(i,i+10);
int temp=0;
for(int j=i;j<i+10;j++){
temp= (temp<<2)| dict.get(s.charAt(j));
}
if (map.containsKey(temp)){
if (map.get(temp)==1){
res.add(convertString(temp));
map.put(temp,-1);
}
}else{
map.put(temp,1);
}
}
return res;

}

public String convertString(int x){
StringBuilder sb=new StringBuilder();
for(int i=0;i>2;
}
return sb.toString();
}
}

Repeated DNA Sequence

Design a file system

Question

Explain the data structures and algorithms that you would use to design an in-memory file system. Illustrate with an example in code where possible.

Solution

A file system consists of Files and Directories. Each Directory contains a set of Files and Directories.

Since Files and Directories share so many characteristics, we’ve implemented them such that they inherit from the same class — Entry.

Design a file system

SQL – Summary

JOIN

INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables

Return nth highest salary from table
+—-+——–+
| Id | Salary |
+—-+——–+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+—-+——–+
Select max(Salary) from Employee emp1
where (N-1)=(select count(DISTINCT(emp2.Salary)) from Employee emp2
where emp2.Salary>emp1.Salary)

Duplicate Email

SELECT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1;
select distinct(p.Email) from Person p, Person q where p.Id!=q.Id and p.Email=q.Email;

Highest Salary In Department
select d.Name Department, e.Name Employee, s.Salary from (
select MAX(e.Salary) Salary, e.DepartmentId from Employee e, Department d where e.DepartmentId=d.Id group by e.DepartmentId
) s, Employee e, Department d where s.Salary=e.Salary and e.DepartmentId=d.Id and e.DepartmentId=s.DepartmentId;

Top N Salary in Depmartemnt
Select d1.Name as Department, e1.Name as Employee, e1.Salary
From Employee e1 ,
Department d1
Where d1.Id=e1.DepartmentId
And (select count(Distinct(Salary)) From Employee e2 where e2.Salary>e1.Salary and e2.DepartmentId=e1.DepartmentId)<N
order by d1.Name ASC, e1.Salary DESC

Delete duplicate Emails
DELETE FROM p1 USING Person p1 INNER JOIN Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id;

TO_DAYS — date conversion
TO_DAYS(today)=TO_DAYS(yesterday)+1

SQL – Summary