Facebook Interview Question for Software Engineers


Country: Singapore
Interview Type: Written Test




Comment hidden because of low score. Click to expand.
1
of 1 vote

/*
Clarification: 
input intervals are half open "[)"

Solution:
there are two fundamental different approaches I considered:
1) sorting the intervals, start with i = 0:
   - the interval i turns it on
   - it stays on as long as there are intervals j > i that 
     start before the last end time of all intervals [i..j]
   - i = j + 1, repeat until i >= n

   this is O(lg(n)) time and O(1) space

2) if we know we care only about 24 hours and the time resolution 
   is an hour, we can create a come / leave array and count the 
   hours where more than 0 people are in the room:
   - create array a[0..23] initialize with 0, 
     peopleintheroom = 0, usedHours = 0
   - for each interval: a[start]++ a[end]--
   - for i = 0 to 23: 
    	peopleintheroom += a[i]
		if(peopleintheroom > 0) usedHours++

   this is still O(1) space, if its always 24 hours ... and 
   O(n) runtime where n is the number of intervals in the input    

1) is better if there are generally fewer than h*lg(h) intervals 
   where h is the number of time slices the potential interval 
   range is divided into (e.g. 24 hours) 
2) is better if memory is not an issue and there are many more 
   intervals than time slices  
*/

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <cassert>

using namespace std;

// helper struct to deal with interval
struct Interval
{
	int start_;
	int end_;

	Interval() : Interval(0, 0) { }
	Interval(int start, int end) : start_(start), end_(end) { }
};

// Option 1)
int getUsedHours(const vector<Interval>& ivals)
{
	vector<Interval> intervals(ivals);
	sort(intervals.begin(), intervals.end(), 
		[](const Interval& a,  const Interval& b) { return a.start_ < b.start_; });

	int i = 0;
	int totalHours = 0;
	while(i < intervals.size())
	{
		int start = intervals[i].start_;
		int end = intervals[i].end_;
		i++;
		while(i < intervals.size() && intervals[i].start_ < end)
		{
			end = max(end, intervals[i].end_);
			i++;
		}
		totalHours += end - start;
	}
	return totalHours;
}

// Option 2)
int getUsedHoursLin(const vector<Interval>& ivals)
{
	vector<int> change(24, 0);

	for(Interval i : ivals) 
	{
		assert(i.start_ < i.end_ && i.end_ < 24);
		change[i.start_] ++;
		change[i.end_] --;
	}

	int hours = 0;
	int p = 0;
	for(int c : change)
	{
		p += c;
		if(p > 0) hours++;
	}

	return hours;
}

int main()
{
	cout << "case 1 with sort: " << getUsedHours(vector<Interval>{ {1, 4}, {2, 3}}) << endl;
	cout << "case 2 with sort: " << getUsedHours(vector<Interval>{ {4, 6}, {1, 2} }) << endl;
	cout << "case 3 with sort: " << getUsedHours(vector<Interval>{ {1, 4}, {6, 8}, {2, 4}, {7, 9}, {10, 15}}) << endl;

	cout << "case 1 linear: " << getUsedHoursLin(vector<Interval>{ {1, 4}, {2, 3}}) << endl;
	cout << "case 2 linear: " << getUsedHoursLin(vector<Interval>{ {4, 6}, {1, 2}}) << endl;
	cout << "case 3 linear: " << getUsedHoursLin(vector<Interval>{ {1, 4}, {6, 8}, {2, 4}, {7, 9}, {10, 15}}) << endl;			
}

- Chris December 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package facebook;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class TvProblem {

public static void tvOn(ArrayList<String> timeInterval) {
HashMap<Integer, Integer> map = new HashMap<>();
for (String s : timeInterval) {
s = s.replaceAll("[()]", "");
String[] interval = s.split(",");
map.put(Integer.valueOf(interval[0]), Integer.valueOf(interval[1]));
}
int newStart;
int newEnd;
Set<Integer> startTime = map.keySet();
ArrayList<Integer> start = new ArrayList<>(startTime);
Collections.sort(start);
for (int k = 0; k < start.size(); k++) {
if (start.get(k) == -1)
continue;
for (int i = k + 1; i < start.size(); i++) {
if (start.get(i) == -1)
continue;

if (start.get(i) < map.get(start.get(k))) {

newStart = start.get(k);
newEnd = Math.max(map.get(start.get(k)), map.get(start.get(i)));
map.remove(start.get(i));
start.set(i, -1);
map.put(newStart, newEnd);
}

}

}
int sum = 0;
for (Entry entry : map.entrySet()) {
int x = (int) entry.getKey();
int y = (int) entry.getValue();
sum += y - x;
}
System.out.println(sum);
}

public static void main(String[] args) {
ArrayList<String> timeInterval = new ArrayList<String>();
timeInterval.add("(1,4)");
timeInterval.add("(2,9)");
timeInterval.add("(5,8)");
timeInterval.add("11,15");
timeInterval.add("21,25");
tvOn(timeInterval);

}
}

- Arpit October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package facebook;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class TvProblem {

	public static void tvOn(ArrayList<String> timeInterval) {
		HashMap<Integer, Integer> map = new HashMap<>();
		for (String s : timeInterval) {
			s = s.replaceAll("[()]", "");
			String[] interval = s.split(",");
			map.put(Integer.valueOf(interval[0]), Integer.valueOf(interval[1]));
		}
		int newStart;
		int newEnd;
		Set<Integer> startTime = map.keySet();
		ArrayList<Integer> start = new ArrayList<>(startTime);
		Collections.sort(start);
		for (int k = 0; k < start.size(); k++) {
			if (start.get(k) == -1)
				continue;
			for (int i = k + 1; i < start.size(); i++) {
				if (start.get(i) == -1)
					continue;

				if (start.get(i) < map.get(start.get(k))) {

					newStart = start.get(k);
					newEnd = Math.max(map.get(start.get(k)), map.get(start.get(i)));
					map.remove(start.get(i));
					start.set(i, -1);
					map.put(newStart, newEnd);
				}

			}

		}
		int sum = 0;
		for (Entry entry : map.entrySet()) {
			int x = (int) entry.getKey();
			int y = (int) entry.getValue();
			sum += y - x;
		}
		System.out.println(sum);
	}

	public static void main(String[] args) {
		ArrayList<String> timeInterval = new ArrayList<String>();
		timeInterval.add("(1,4)");
		timeInterval.add("(2,9)");
		timeInterval.add("(5,8)");
		timeInterval.add("11,15");
		timeInterval.add("21,25");
		tvOn(timeInterval);

	}
}

- Arpit October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package facebook;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class TvProblem {

	public static void tvOn(ArrayList<String> timeInterval) {
		HashMap<Integer, Integer> map = new HashMap<>();
		for (String s : timeInterval) {
			s = s.replaceAll("[()]", "");
			String[] interval = s.split(",");
			map.put(Integer.valueOf(interval[0]), Integer.valueOf(interval[1]));
		}
		int newStart;
		int newEnd;
		Set<Integer> startTime = map.keySet();
		ArrayList<Integer> start = new ArrayList<>(startTime);
		Collections.sort(start);
		for (int k = 0; k < start.size(); k++) {
			if (start.get(k) == -1)
				continue;
			for (int i = k + 1; i < start.size(); i++) {
				if (start.get(i) == -1)
					continue;

				if (start.get(i) < map.get(start.get(k))) {

					newStart = start.get(k);
					newEnd = Math.max(map.get(start.get(k)), map.get(start.get(i)));
					map.remove(start.get(i));
					start.set(i, -1);
					map.put(newStart, newEnd);
				}

			}

		}
		int sum = 0;
		for (Entry entry : map.entrySet()) {
			int x = (int) entry.getKey();
			int y = (int) entry.getValue();
			sum += y - x;
		}
		System.out.println(sum);
	}

	public static void main(String[] args) {
		ArrayList<String> timeInterval = new ArrayList<String>();
		timeInterval.add("(1,4)");
		timeInterval.add("(2,9)");
		timeInterval.add("(5,8)");
		timeInterval.add("11,15");
		timeInterval.add("21,25");
		tvOn(timeInterval);

	}
}

- Anonymous October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

One approach is to sort the intervals as per start time and then count the duration of all intervals(after considering overlaps). This is O(nlogn). Another approach is to take an bool array of size equal to max time and mark it on/off. This is O(n) time O(n) space approach.

- vishalsahunitt October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Little trick is we don't have to track each person. we just need to count no of person present in room at any point of time.

package smapleQuestionsAlgorithms;

import java.util.Arrays;

public class FacebookQuestion {

	public static int hoursWatched(int[] in,int[] out){
		int count=0;
		int i=0,j=0;
		int watchedHours=0;
		for(int h=0;h<=24;h++){
			while( i<in.length && in[i]==h ){
				i++;
				count++;
			}
			while(j<out.length && out[j]==h ){
				j++;
				count--;
			}
			if(count>0){
				watchedHours++;
			}
		}
		return watchedHours;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] in={1,6,2,7,10};
		int[] out={4,8,4,9,15};
		Arrays.sort(in);
		Arrays.sort(out);
		System.out.println(hoursWatched(in, out));
	}

}

- sivapraneethalli October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Your solution is dependent on the order in which inputs are given. If I place interval 1-4 and 2-4 at the end of the array, your algo will miss this intervals.

Try with

int[] in={6,7,10,1, 2};
		int[] out={8,9,15,4, 4};

- pritesh October 29, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def calculateMaxInterval(pairList):
  watchList = WatchList()
  for start, end in pairList:
    watchList.add(start, end)
  return watchList.getWatchTime()

class WatchList:
  def __init__(self):
    self.interval = {}
  def add(self, start, end):
    oldEnd = self.interval.get(start) 
    if oldEnd == None: self.interval[start] = end
    elif oldEnd < end:
      self.interval[start] = end  
  def getWatchTime(self):
     time = 0
     lastEndTime = 0
     for s, e in sorted(self.interval.items()):
       newS = max(lastEndTime, s)
       t = e - newS
       if t > 0: time += t
       lastEndTime = max(e, lastEndTime)
     return time

- friendlyJLee October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// ZoomBA avoids coding... thus :
def do_fb( l ){
  sorta ( l ) :: {  $.left.0 < $.right.0  }
  // merge and sum intervals 
  #(s,last) = fold ( [1:#|l|] , [ 0 , l[0] ] ) -> {
     prev = $.prev[1] ; cur = l[$.item] 
     if ( prev.1 >= cur.0  ){ // there is overlap 
       // but, is current fully inside previous?
       if ( prev.1 < cur.1 ){
         // merge them 
         $.prev[1] =  [ prev.0 , cur.1 ] 
       }
     } else {
        // update sum 
        $.prev.0 += ( prev.1 - prev.0 )
        $.prev.1 = cur 
     } 
     $.prev 
  }
  s += ( last.1 - last.0 )
}
input = [[1,4], [6,8], [2,4], [7,9], [10, 15]] 
println ( do_fb( input ) )

- NoOne October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class TimeFrame
{
	public int Start;
	public int End;
}

private class TimeFrameComparer : IComparer<TimeFrame>
{
	public int Compare(TimeFrame x, TimeFrame y)
	{
		return x.Start.CompareTo(y.Start);
	}
}

public int GetWorkingTime(TimeFrame[] frames)
{
	if (frames == null || frames.Length == 0)
		return 0;

	var result = new List<TimeFrame>();
	var c = frames[0];

	for (int i=1; i < frames.Length; i++)
	{
		if (frames[i].Start < c.End)
			c = new TimeFrame { Start = c.Start, End = Math.Max(c.End, frames[i].End) };
		else
		{
			result.Add(c);
			c = frames[i];
		}
	}

	result.Add(c);

	int total = 0;
	foreach (var item in result)
		total += item.End - item.Start + 1;

	return total;
}

- hnatsu October 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def TVOnTime(arr):
	if len(arr) == 1:
		return arr[0][1] - arr[0][1]
	arr.sort()
	print arr
	previous = None
	total = 0
	for person in arr:
		if previous == None:
			previous = person
			total += person[1] - person[0]
			continue
		if person[0] == previous[0]:
			if previous[1] > person[1]:
				total += person[1] - previous[1]
				previous = person
		elif person[0] < previous[1]:
			if person[1] <= previous[1]:
				continue
			else:
				total += person[1] - previous[1]
				previous = person
		else:
			total += person[1] - person[0]
			previous = person
	return total

- asd October 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

add values between all the time ranges i.e(starttime to endtime-1 ) to hashset .
..size of the hashset will be the tottal working time of the television

import java.util.ArrayList;
import java.util.HashSet;

public class tottalrunningtime {

	

	public static class time {
		int start;
		int end;

		time(int startm, int end) {
			this.start = startm;
			this.end = end;
		}

	}

	public static void main(String[] args) {
		ArrayList<time> timeranges = new ArrayList<time>();
		timeranges.add(new time(1, 4));
		timeranges.add(new time(6, 8));
		timeranges.add(new time(2, 4));
		timeranges.add(new time(7, 9));
	    timeranges.add(new time(10, 15));
		HashSet<Integer> ontimecounter = new HashSet<Integer>();
		for (int i = 0; i < timeranges.size(); i++) {

			for (int j = timeranges.get(i).start; j < timeranges.get(i).end; j++) {
				ontimecounter.add(j);
			}

		}

		System.out.println(ontimecounter.size());
	}

}

- sj October 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MergeIntervals {

public class Interval {
int start, end;

Interval(int start, int end) {
this.start = start;
this.end = end;
}
}

public static void main(String[] args) {
MergeIntervals obj = new MergeIntervals();
obj.test();
}

public void test() {
Interval i1 = new Interval(1,3);
Interval i2 = new Interval(8,10);
Interval i3 = new Interval(2,6);

List<Interval> intervals = new ArrayList<>();
intervals.add(i1);
intervals.add(i2);
intervals.add(i3);

List<Interval> merged = merge(intervals);
int longest = getLongestInterval(merged);
System.out.println(longest);
}

public List<Interval> merge(List<Interval> intervals) {
List<Interval> result = new ArrayList<>();
if (intervals == null || intervals.size() == 0)
return result;

Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
if (o1.start != o2.start) {
return o1.start - o2.start;
} else {
return o1.end - o2.end;
}
}
});

Interval pre = intervals.get(0);
for (int i=1; i<intervals.size(); i++) {
Interval curr = intervals.get(i);
if (pre.end < curr.start) { // gap
result.add(pre);
pre = curr;
} else {
Interval merged = new Interval(pre.start, curr.end);
pre = merged;
}
}
result.add(pre);
return result;
}

public int getLongestInterval(List<Interval> intervals) {
int longest = 0;

for (int i=0; i< intervals.size(); i++) {
Interval curr = intervals.get(i);
longest = Math.max(longest, curr.end - curr.start);
}
return longest;
}
}

- ivyshushu November 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static class Pair implements Comparable<Pair> {
        int first;
        int second;

        public Pair(int first, int second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public int compareTo(Pair p) {
            return first - p.first;
        }
    }

    public static int solution(List<Pair> times) {
        Collections.sort(times);
        List<Pair> segments = new ArrayList<>();
        for (Pair pair : times) {
            if (segments.isEmpty()) {
                segments.add(pair);
            } else {
                boolean added = false;
                for (Pair watchingTime : segments) {
                    if (pair.first <= watchingTime.second) {
                        watchingTime.second = watchingTime.second > pair.second ? watchingTime.second : pair.second;
                        added = true;
                        break;
                    }
                }
                if (!added) {
                    segments.add(pair);
                }
            }
        }
        int result = 0;
        for (Pair pair : segments) {
            result += pair.second - pair.first;
        }
        return result;
    }

- Long November 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming that the input set does not span days we can maintain an array of int for each hour. Initialize all the values to zero. Set array[index] to 1 for all values of index >=starttime and <= endtime.
Once all the people are covered. Add the number of '1's in the array.

- Anonymous November 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public TvAndWatch()
        {
            var input = new Queue<int[]>();
            input.Enqueue(new int[] { 1, 4});
            input.Enqueue(new int[] { 6, 8 });
            input.Enqueue(new int[] { 2, 4 });
            input.Enqueue(new int[] { 7, 9 });
            input.Enqueue(new int[] { 10, 15 });

            var store = new int[24];

            while (input.Count > 0)
            {
                var d = input.Dequeue();

                for (int i = d[0] + 1; i <= d[1]; i++)
                {
                    store[i] = 1;
                }
            }
            Console.WriteLine(store.Sum());
        }

- Srini November 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public TvAndWatch()
{
var input = new Queue<int[]>();
input.Enqueue(new int[] { 1, 4});
input.Enqueue(new int[] { 6, 8 });
input.Enqueue(new int[] { 2, 4 });
input.Enqueue(new int[] { 7, 9 });
input.Enqueue(new int[] { 10, 15 });

var store = new int[24];

while (input.Count > 0)
{
var d = input.Dequeue();

for (int i = d[0] + 1; i <= d[1]; i++)
{
store[i] = 1;
}
}
Console.WriteLine(store.Sum());
}

- Srini November 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public TvAndWatch()
        {
            var input = new Queue<int[]>();
            input.Enqueue(new int[] { 1, 4});
            input.Enqueue(new int[] { 6, 8 });
            input.Enqueue(new int[] { 2, 4 });
            input.Enqueue(new int[] { 7, 9 });
            input.Enqueue(new int[] { 10, 15 });

            var store = new int[24];

            while (input.Count > 0)
            {
                var d = input.Dequeue();

                for (int i = d[0] + 1; i <= d[1]; i++)
                {
                    store[i] = 1;
                }
            }
            Console.WriteLine(store.Sum());
        }

- Srini November 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int totalIntervalTime(Interval[] Intervals){
	int[] startTime = new int[Intervals.length];
	int[] endTme = new int[Intervals.length];
	for(int i = 0; i < Intervals.length; i++){
		startTime[i] = Intervals.start;
		endTime[i] = Intervals.end;
	}
	Arrays.sort(startTime);
	Arrays.sort(endTime);
	int count = 0;
	int startIdx = 0;
	int endIdx = 0;
	int start = 0;
	int end = 0;
	int total = 0;
	while(startIdx < Intervals.length && endIdx < Intervals.length){
		if(startTime[startIdx] <= endTime[endIdx]){
			if(count == 0) start = startTime[startIdx];
			startIdx++;
			count++;
		}else{
			count--;
			if(count == 0){
				total += endTime[endIdx] - start;
				end = 0;
			}else{
				end = Math.max(end, endTime[endIdx]);
			}
			endIdx++;
		}
	}
	if(count != 0){
		total += Math.max(end, findMax(endTime, endIdx)) - sum;
	}
	
	return total;
}

- Dinesh November 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is an Objective-C solution in O(n), the key is sort all intervals first and merge those who overlap each other

-(int)getTotalTimeFromIntervals:(NSMutableArray *)array{
    
    
    NSMutableArray *result = [NSMutableArray new];
    
    //  FIRST SORT ALL INTERVALS
    array = [array sortedArrayUsingComparator:^(id a, id b){
       
        return [[a objectAtIndex:0] compare:[b objectAtIndex:0]];
    }];
    
    NSMutableArray *temp = array[0];
    NSMutableArray *current;
    
    //  TRAVERSE ALL INTERVALS TO MERGE IN CASE SOME OF THEM OVERLAP
    for(int i = 0; i < [array count]; i++){
        
        current = array[i];
        
        if([current[0] intValue] > [temp[1] intValue]){
            
            [result addObject:temp];
            temp = current;
        }
        else{
            
            NSMutableArray *merged = [[NSMutableArray alloc] initWithObjects:
                                      [NSNumber numberWithInt:[temp[0] intValue]],
                                      [NSNumber numberWithInt:fmax([temp[1] intValue], [current[1] intValue])], nil];
            temp = merged;
        }
        
        
    }
    
    [result addObject:temp];
    
    //  SUM OUR FINAL INTERVALS
    int total = 0;
    for(int i = 0; i < [result count]; i++){
        
        total += [result[i][1] intValue] - [result[i][0] intValue];
    }
    
    return total;
}

- oscarsanchez1937 November 09, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int tvOn(int[][] intervals) {
      if (intervals.length == 0)  return 0;
      if (intervals.length == 1) return intervals[0][1] - intervals[0][0];
      
      Arrays.sort(intervals, 0, intervals.length, new Comparator<int[]>() {
        public int compare(int[] left, int[] right) {
          return left[0] - right[0];
        }
      });
      

      int[] last = intervals[0];
      int res = intervals[0][1] - intervals[0][0];
      for (int i = 1; i < intervals.length; i++) {
        int[] cur = intervals[i];
        if (cur[0] <= last[1]) {
          if (cur[1] > last[1]) {
            res += cur[1] - last[1];
            last = new int[]{last[0], cur[1]};
          } else {
            continue;
          }
        } else {
          res += cur[1] - cur[0];
          last = cur;
        }
      }
      
      return res;
    }

- tryhard November 13, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use a HashSet to store all the hours when the TV is on. Value returned is the size of the HashSet.

int solution(ArrayList<int[]> list){
HashSet<Integer> set = new HasSet<Integer>();
for (int i = 0; i < set.size(); i++){
int[] interval = list.get(i);
int start = interval[0];
int end = interval[1];
for (int j = start+1; j <= end; j++){
if (!set.contains(j))
set.add(j);
}
}
return set.size();
}

- JHua November 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class TimeTuples{
public void solve() {
  List<Tuple<int,int>> list = new List<Tuple<int,int>>();
    list.Add(Tuple.Create(1,4));
    list.Add(Tuple.Create(2,3));
    list.Add(Tuple.Create(7,8));
    list.Add(Tuple.Create(5,9));
    list.Add(Tuple.Create(14,18));
    list.Add(Tuple.Create(71,83));
    list.Add(Tuple.Create(7,11));
    list.Add(Tuple.Create(3,4));
    list.Add(Tuple.Create(7,8));
    
    int largest = 0;
    foreach(Tuple<int,int> p in list) {
       if(p.Item1+p.Item2 > largest){
         largest = p.Item2;
       }
    }
    
    int[] timeline = new int[largest+1];
    foreach(Tuple<int,int> p in list) {
      for(int i=p.Item1+1;i<=p.Item2;++i){
        if(timeline[i]==0)
          timeline[i]=p.Item2-p.Item1;
      }
    }
    
    int largestSeg = 0;
    foreach(var v in timeline){
      if(v>largestSeg) {
        largestSeg = v;
      }
      Console.Write(" "+v);
    }
    Console.WriteLine("\n\n"+largestSeg);
}
}

- BlastCap November 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think interval tree is the good solution. The node save the largest watch time。

- cherrytino91 December 10, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int findLongestWatchingPeriod(List<Pair<Integer, Integer>> intervals) {
        int [] counter = new int[24];
        for (Pair<Integer, Integer> interval : intervals) {
            counter[interval.fst]++;
            counter[interval.snd]--;
        }
        int totalTime = 0;
        int watchers = 0;
        for (int aCounter : counter) {
            watchers += aCounter;
            if (watchers > 0) {
                totalTime++;
            }
        }

        return totalTime;
    }

    public static void prepareIntervals() {
        int total = findLongestWatchingPeriod(
            Arrays.asList(
                new Pair<Integer, Integer>(1, 4),
                new Pair<Integer, Integer>(6, 8),
                new Pair<Integer, Integer>(2, 4),
                new Pair<Integer, Integer>(7, 9),
                new Pair<Integer, Integer>(10, 15)
            )
        );
        System.out.println("Total hours " + total);
        int total2 = findLongestWatchingPeriod(
            Arrays.asList(new Pair<Integer, Integer>(4, 6), new Pair<Integer, Integer>(1, 2))
        );
        System.out.println("Total hours " + total2);
        int total3 = findLongestWatchingPeriod(
            Arrays.asList(new Pair<Integer, Integer>(1, 4), new Pair<Integer, Integer>(2, 3))
        );
        System.out.println("Total hours " + total3);
    }

- ShehabiX December 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static int findLongestWatchingPeriod(List<Pair<Integer, Integer>> intervals) {
        int [] counter = new int[24];
        for (Pair<Integer, Integer> interval : intervals) {
            counter[interval.fst]++;
            counter[interval.snd]--;
        }
        int totalTime = 0;
        int watchers = 0;
        for (int aCounter : counter) {
            watchers += aCounter;
            if (watchers > 0) {
                totalTime++;
            }
        }

        return totalTime;
    }

    public static void prepareIntervals() {
        int total = findLongestWatchingPeriod(
            Arrays.asList(
                new Pair<Integer, Integer>(1, 4),
                new Pair<Integer, Integer>(6, 8),
                new Pair<Integer, Integer>(2, 4),
                new Pair<Integer, Integer>(7, 9),
                new Pair<Integer, Integer>(10, 15)
            )
        );
        System.out.println("Total hours " + total);
        int total2 = findLongestWatchingPeriod(
            Arrays.asList(new Pair<Integer, Integer>(4, 6), new Pair<Integer, Integer>(1, 2))
        );
        System.out.println("Total hours " + total2);
        int total3 = findLongestWatchingPeriod(
            Arrays.asList(new Pair<Integer, Integer>(1, 4), new Pair<Integer, Integer>(2, 3))
        );
        System.out.println("Total hours " + total3);
    }

- shehabic December 19, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#! /usr/bin/env ruby

def get_tv_len(inputs)
  on_arr = Array.new
  inputs.sort! { |x, y| x[0] <=> y[0] }
  
  inputs.each do |latest|
    if on_arr.empty?
      on_arr.push(latest)
      next
    end
    
    last_el = on_arr[-1]
    if last_el[1] < latest[0]
      on_arr.push(latest)
    
    elsif last_el[1] < latest[1]
      last_el[1] = latest[1]
    
    end
  end
  
  on_len = on_arr.map { |on| on[1] - on[0] }
  return on_len.reduce(0, :+)
end

inputs = [[1,4], [6,8], [2,4], [7,9], [10, 15]]
p get_tv_len(inputs)

- jimmychu0807 December 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a=[(4,6),(1,2)]
x=0
d1=0
d2=0
for i in sorted(a):
if i[0]>=x:
d1=d1+i[1]-i[0]
elif i[1]>x:
d2=d2+i[1]-x
else:
pass
x=i[1]
print d1+d2

- Anonymous December 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from collections import Counter
times = [(1,4), (6,8), (2, 4), (7,9), (10,15)]

room = Counter()
for time in times:
    room[time[0]] += 1
    room[time[1]] -= 1

room = room.items()
room.sort(key=lambda k:k[0])

count = 0
tv = 0
last_event = 0
for event in room:
    if count:
        tv += (event[0] - last_event)
    last_event = event[0]
    count += event[1]

print tv

- Nitish Garg January 02, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayList;
import java.util.HashSet;

public class TVHourProblem {
public static void main(String[] args) {

HashSet<Integer> set=new HashSet<>();
ArrayList<int[]> list=new ArrayList<>();
list.add(new int[] {1,4});

for(int i=0;i<list.size();i++){
int[] obj=list.get(i);
int in=obj[0];
int out=obj[1];
for(int j=in+1;j<=out;j++){
if(!set.contains(j)){
set.add(j);
}
}
}
System.out.println("TV ON: "+set.size());
}
}

- Md Omar Faroque January 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayList;
import java.util.HashSet;

public class TVHourProblem {
	public static void main(String[] args) {
	
		HashSet<Integer> set=new HashSet<>();
		ArrayList<int[]> list=new ArrayList<>();
		list.add(new int[] {1,4});
		
		for(int i=0;i<list.size();i++){
			int[] obj=list.get(i);
			int in=obj[0];
			int out=obj[1];
			for(int j=in+1;j<=out;j++){
				if(!set.contains(j)){
					set.add(j);
				}
			}
		}
		System.out.println("TV ON: "+set.size());
	}
}

- Md Omar Faroque January 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

javascript:

function tvOn(arr) {
	var on = {};
	var len = arr.length;
	var total = 0;
	for (var i = 0; i < len; i++) {
		var istart = arr[i][0];
		var iend = arr[i][1];
		for (var j = istart; j < iend; j++) {
			if (typeof on[j] !== 'undefined') {
				continue;
			}
			on[j] = true;
			total++;
		}
	}
	return total;
}

- jbxx January 23, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More