3-line Java 8 solution using Map and reduce

  • 1

    The body is 3-line.

    public int getImportance(List<Employee> employees, int id) {
        Map<Integer, Employee> map = employees.stream().collect(Collectors.toMap(e -> e.id, e -> e));
        return helper(map, id);
    private int helper(Map<Integer, Employee> map, int id) {
        return map.get(id).importance + map.get(id).subordinates.stream()
            .reduce(0, (s1, s2) -> s1 + helper(map, s2), (s1, s2) -> s1 + s2);

  • 0

    @yilongwang Cool solution!

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.