Problem overview
oldestPet receives a list of pets. Each pet is a Pair<String, Int>: its name, then its age. The function returns the name of the oldest pet, as a String. If several pets share the oldest age, the one that comes first in the list wins.
For [("Rex", 4), ("Bella", 7), ("Max", 2)] the answer is "Bella". For [("Luna", 3), ("Coco", 9), ("Milo", 9)] Coco and Milo are tied at 9, so the answer is "Coco". A list with one pet, [("Kiki", 0)], gives "Kiki". The list always has at least one pet.
Approach
Keep the best pet found so far in a variable, and compare every pet with it. When a pet is older, it replaces the variable. Store the whole pair, not only the age: the name has to come along, because it is what you return at the end.
Start the variable at the first pet, pets[0]. That is a real pet and the oldest you have seen so far, before looking at any other. Starting at an age like 0 would need a made-up name.
Step by step
- Declare
oldestwithvarand set it topets[0]. It is avarbecause it will be replaced. - Loop over the pets with
for (pet in pets). - Inside, compare ages. A pair's age is its second value, so the test is
pet.second > oldest.second. - When the test is true, set
oldest = pet. - After the loop, return
oldest.first, the name.
The solution in Kotlin
class Solution {
fun oldestPet(pets: List<Pair<String, Int>>): String {
var oldest = pets[0]
for (pet in pets) {
if (pet.second > oldest.second) {
oldest = pet
}
}
return oldest.first
}
}
On the three examples it returns:
Bella
Coco
Kiki
The comparison is strict (>, not >=). In the second example, when the loop reaches Milo, his age 9 is equal to Coco's 9, not greater, so Coco stays. With >= the last of the tied pets would win, and the answer would be Milo.
The type Pair<String, Int> tells you what each slot holds: first is a String and second is an Int. Mixing them up is a compile error, since you can't return an Int where a String is expected.
A trace of the tie
For [("Luna", 3), ("Coco", 9), ("Milo", 9)], this is who is the oldest after each pet is looked at:
Luna: oldest is Luna
Coco: oldest is Coco
Milo: oldest is Coco
Luna replaces nothing (she is the start), Coco is older than Luna, and Milo is only equal to Coco, so Coco stays. Changing the test to >= makes the function return Milo for this list.
The list is read once, so the work grows in step with the number of pets.
Edge cases and common mistakes
- Using
>=. It breaks the tie rule. - Comparing the pair itself.
pet > oldestdoesn't compile: the compiler reports an unresolved reference tocompareTo, because pairs have no order. Compare theirsecondvalues. - Returning
oldest. That is a pair, but the function's return type isString. Returnoldest.first. - Storing only the age. Then the name is lost by the end of the loop.
- A one-pet list works without a special case: the loop compares the pet with itself, nothing changes, and its name is returned.
