502. Check If Target URL Is Reachable by Following Links
Asked in
Check If Target URL Is Reachable by Following Links

You are given a list of links between web pages. Each link is a string "fromUrl,toUrl", which means the page fromUrl has a link to the page toUrl. A link can only be followed in one direction, from fromUrl to toUrl.

Starting at the URL startUrl, you may follow any number of links, one after another. Check if the target URL targetUrl is reachable from startUrl this way.

Method Signature

boolean isReachable(List<String> links, String startUrl, String targetUrl)
  • Return true if targetUrl is reachable from startUrl by following links, otherwise return false.
  • If startUrl is equal to targetUrl, return true, since no link needs to be followed.
  • Two URLs are the same only if their strings are exactly equal.
  • startUrl or targetUrl might not appear in any link.
  • Links may repeat, a page may link to itself, and links may form cycles.

Constraints

  • 1 ≤ links.size() ≤ 100,000
  • 1 ≤ fromUrl.length(), toUrl.length(), startUrl.length(), targetUrl.length() ≤ 100
  • fromUrl, toUrl, startUrl and targetUrl contain only lowercase English letters, digits and the characters '.', '/', ':', '-' and '_'.

Examples

Example 1

Input: isReachable(links = ["shop.com,shop.com/men", "shop.com/men,shop.com/men/shoes", "shop.com/women,shop.com/women/bags"], startUrl = "shop.com", targetUrl = "shop.com/men/shoes")

Output: true

Explanation: shop.com → shop.com/men → shop.com/men/shoes.

Example 2

Input: isReachable(links = ["shop.com,shop.com/men", "shop.com/men,shop.com/men/shoes", "shop.com/women,shop.com/women/bags"], startUrl = "shop.com", targetUrl = "shop.com/women/bags")

Output: false

Explanation: From shop.com, following links leads only to shop.com/men and then shop.com/men/shoes. None of these pages has a link to shop.com/women or shop.com/women/bags.

Example 3

Input: isReachable(links = ["shop.com,shop.com/men", "shop.com/men,shop.com/men/shoes", "shop.com/women,shop.com/women/bags"], startUrl = "shop.com/men/shoes", targetUrl = "shop.com")

Output: false

Explanation: Links work in one direction only. shop.com/men/shoes has no link to any other page.

Example 4

Input: isReachable(links = ["blog.io,blog.io/posts", "blog.io/posts,blog.io/post/7", "blog.io/post/7,blog.io", "blog.io/post/7,news.io"], startUrl = "blog.io/posts", targetUrl = "news.io")

Output: true

Explanation: blog.io/posts → blog.io/post/7 → news.io. The cycle blog.io → blog.io/posts → blog.io/post/7 → blog.io does not change the answer.

Example 5

Input: isReachable(links = ["a.org,b.org"], startUrl = "c.org", targetUrl = "c.org")

Output: true

Explanation: startUrl is equal to targetUrl, so no link needs to be followed, even though c.org is not in any link.



Please use Laptop/Desktop or any other large screen to add/edit code.