Problem overview
oldestPet(pets) receives an array of pets. Each pet is a two-item array, [name, age], such as ["Rex", 4]. The function returns the name of the oldest pet. If several pets share the oldest age, it returns the one that comes first.
For [["Rex", 4], ["Bella", 7], ["Max", 2]] the answer is "Bella". For [["Luna", 3], ["Coco", 9], ["Milo", 9]] the answer is "Coco", because Coco and Milo are both 9 and Coco is first.
Approach
Remember the oldest pet seen so far, and compare each pet with it. Keep the whole pair, not just the age, so the name comes along. A pet's age is at index 1 and its name at index 0.
The tie rule comes from the comparison. Replace the stored pet only when the new one is strictly older (>). On a tie the stored pet, which came earlier, stays. Using >= would let a later pet win a tie.
Step by step
- Set
oldesttopets[0]. It is the oldest pet seen so far, before the loop looks at the others. - Loop over
petswithfor...of; each item is one pair,pet. - If
pet[1] > oldest[1], this pet is older. - Then set
oldest = pet. - After the loop, return
oldest[0], the name.
The solution in JavaScript
class Solution {
oldestPet(pets) {
let oldest = pets[0];
for (let pet of pets) {
if (pet[1] > oldest[1]) {
oldest = pet;
}
}
return oldest[0];
}
}
In JavaScript the pair is an array, so the pairs are written with square brackets. The first loop pass compares pets[0] with itself, which changes nothing. Running the three examples returns Bella, Coco and Kiki (for [["Kiki", 0]]).
Tracing the tie example
For [["Luna", 3], ["Coco", 9], ["Milo", 9]], this is the name of oldest after each pet is checked:
Luna -> oldest=Luna
Coco -> oldest=Coco
Milo -> oldest=Coco
Coco's 9 beats Luna's 3, so Coco replaces Luna. Milo's 9 is not greater than Coco's 9, so Coco stays. If the test were >=, Milo would replace Coco and the function would return "Milo", which fails the lesson's tests.
Complexity
Each pet is compared once, so the time is O(n) for n pets. The function stores only one pair at a time, so the extra space is O(1). Sorting the pets by age and taking the end would also find the answer, but it does more work than one pass needs.
Edge cases and common mistakes
- A single pet. The loop never replaces
oldest, and the first pet's name is returned. An age of 0 is fine. - Ties. Use
>, not>=, to keep the first of equal ages. - Tracking only the age. A variable holding just the biggest age tells you how old the oldest pet is, but not whose name to return. Keeping the pair solves that.
- Returning the pair. The function returns only the name,
oldest[0]. - Swapped indexes. Comparing
pet[0]would compare names, not ages. Strings compare alphabetically, so"Rex" > "Bella"is true, and the first example would return"Rex"instead of"Bella", with no error to point at the mistake.
