educative.io

Probably a better solution

public static String tracePath(Map<String,String> map) {
String result = “”;
String startKey = “”;
for (Map.Entry<String, String> entry : map.entrySet()) {
if (!map.containsValue(entry.getKey())) {
startKey = entry.getKey();
break;
}
}

    while (map.containsKey(startKey)) {
        result = result + startKey + "->" + map.get(startKey) + " , ";
        startKey = map.get(startKey);
    }

    return result;
}

Hi @Hemant_Patidar ,

This is Fatimah Abdullah from Educative.

In response to your feedback, thank you for reaching out to us with your suggestion. Yes, the algorithm you have suggested is correct. It is also more space-efficient than the mentioned solution! In the course, we have used a very straightforward solution, but we really appreciate that you have taken the time to come up with a better version of it. I encourage you to do ahead with this solution.

We hope Educative has inspired to further your learning, and please drop us a note if you have any other questions or concerns.

Best Regards,
Fatimah Abdullah | Developer Advocate
Educative Inc.

1 Like