Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 0 additions & 31 deletions src/DestinationCity1436.java

This file was deleted.

32 changes: 32 additions & 0 deletions src/main/java/com/leetcode/easy/DestinationCity1436.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Tags: Array, Hash Set
package com.leetcode.easy;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DestinationCity1436 {
/*
Given n as the length of paths,

Time complexity: O(n)
We first iterate over paths to populate hasOutgoing, this costs O(n).
Next, we iterate over paths again to find the answer, checking at each step whether candidate is in the hash set, which takes O(1). Thus the iteration costs O(n).

Space complexity: O(n)
hasOutgoing will grow to a size of O(n).
*/
public String destCity(List<List<String>> paths) {
Set<String> hasOutgoing = new HashSet<>();
for (List<String> path : paths) {
hasOutgoing.add(path.get(0));
}
for (List<String> path : paths) {
String candidate = path.get(1);
if (!hasOutgoing.contains(candidate)) {
return candidate;
}
}
return "";
}
}
51 changes: 51 additions & 0 deletions src/test/java/com/leetcode/easy/DestinationCity1436Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.leetcode.easy;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class DestinationCity1436Test {
private DestinationCity1436 solution;

@BeforeEach
void setUp() {
solution = new DestinationCity1436();
}

@Test
void testDestCity_Example1() {
List<List<String>> paths = List.of(
List.of("London", "New York"),
List.of("New York", "Lima"),
List.of("Lima", "Sao Paulo")
);
String expected = "Sao Paulo";
String result = solution.destCity(paths);
assertEquals(expected, result);
}

@Test
void testDestCity_Example2() {
List<List<String>> paths = List.of(
List.of("B", "C"),
List.of("D", "B"),
List.of("C", "A")
);
String expected = "A";
String result = solution.destCity(paths);
assertEquals(expected, result);
}

@Test
void testDestCity_Example3() {
List<List<String>> paths = List.of(
List.of("A", "Z")
);
String expected = "Z";
String result = solution.destCity(paths);
assertEquals(expected, result);
}
}