Most Living People
June 5, 2015
Our strategy is to read the inputs and count the years in a hash table; when the input is exhausted, we scan the hash table and find the maximum years. The only tricky part is that some lines have both birth years and death years but some lines have only a birth year:
$ python Python 2.7.8 (default, Jul 28 2014, 01:34:03) [GCC 4.8.3] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> def judge(filename, currYear): ... f = open(filename, 'r') ... n = int(f.readline()) ... for i in range(n): ... Y = {} ... m = int(f.readline()) ... for j in range(m): ... years = str.split(f.readline()) ... start = int(years[0]) ... stop = int(years[1] if len(years) > 1 else currYear) ... for k in range(start, stop+1): ... if k not in Y: Y[k] = 0 ... Y[k] += 1 ... x = max(Y.values()) ... print sorted([y[0] for y in Y.items() if y[1] == x]) ... >>> judge("judge.txt", 2015) [1948] [1945, 1946, 1947, 1948]
You can run the program at http://ideone.com/Y2LPLC.
In perl – this is what perl was written for!
my $Y = 2015;
my $cases = ;
foreach my $case ( 1..$cases ) {
my $rows = ;
my %years;
foreach my $row ( 1..$rows ) {
$_ = ;
my($s,$e) = split;
$years{$_}++ foreach $s..($e||$Y);
}
my $max = 0;
foreach (values %years) {
$max = $_ if $max < $_;
}
printf "@{[ sort grep {$years{$_}==$max} keys %years ]}\n",
}
I was wondering if there is a better data structure/algorithm to solve this ?
Intersection of intervals and maintaining a count of intersection ?
The above code is written in java and assuming all the validations are true
Haari, I tried a solution with set too. The problem is when there is a range which doesn’t overlap at all (someone noncontemporary).
Try this dataset – there wont be any output.
1(# of cases)
3(# of entries)
2010
1910 1948
1927 1995
Though expected output is 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948.
Prabhu, go through the task once more. The task to print a common year lived by all the people. In your dataset, if you give 2010, it won’t be a common year for all the 3 people since other people died in 1948 and 1995 so there wont be any output.
Consider an inverse problem: you are given a list of birth years and a list of death years for a group of people. The same birth (or death) year may be listed for multiple times if there are more than one birth (or death) in that year. However, the two lists are separate and no names are attached to each year. Please estimate the numbers of years that these people have lived.