You need two storages.
- A dictionnary that maps
bandname
to it's top songname
. Let's call it topBandSong
.
- A dictionnary that maps
(bandname, songname)
to the number of times this song has been played. Let's call it bandSongPopularity
.
With this topSong
is pretty simple (leaving aside the case where nothing is known about the band yet):
Map<String, String> topBandSong = new HashMap();
String topSong(String bandname) {
return topBandSong.get(bandname);
}
The play
function has to update both maps. This is really easy:
Map<String, BigInteger> bandSongPopularity = new HashMap();
void play(String bandname, String songname) {
/* First update bandSongPopularity */
String k = bandname + "\000" + songname;
BigInteger popularity = bandSongPopularity.get(k);
if (popularity == null) {
popularity = BigInteger.valueOf(1);
}
else {
popularity = popularity.add(BigInteger.valueOf(1));
}
bandSongPopularity.put(k, popularity);
/* then update topBandSong */
String top = topSong(bandname);
if (top == null) {
topBandSong.put(bandname, songname);
}
else {
String topK = bandname + "\000" + top;
BigInteger topPopularity = bandSongPopularity.get(topK);
/* topPopularity can not be NULL */
if (popularity.compareTo(topPopularity) > 0) {
topBandSong.put(bandname, songname);
}
}
/* Finally really play this song. But this is left as an exercise ;-) */
}
The complexity is the one of the underlying dictionnary you choose, i.e. a tree or a hash.
Note that the code reserves character number 0.