Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Reconstruct Itinerary

Posted on August 21, 2019July 26, 2020 by braindenny

Reconstruct Itinerary



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #dfs, #backtracking, #graph

Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.

Note:

  1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary [“JFK”, “LGA”] has a smaller lexical order than [“JFK”, “LGB”].
  2. All airports are represented by three capital letters (IATA code).
  3. You may assume all tickets form at least one valid itinerary.

Example 1:

Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Output: ["JFK", "MUC", "LHR", "SFO", "SJC"]

Example 2:

Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"].
             But it is larger in lexical order.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/reconstruct-itinerary
// Basic Ideas: dfs
//  Notice:
//    To avoid loop, edge can't be used twice
//    There might be duplicate tickets
//
// Complexity: Time ? Space ?
import "sort"
func dfs(node string, m map[string][]string, visited map[string][]bool, res *[]string, count int) bool {
    if len(*res) == count { return true }
    for i, node2 := range m[node] {
        if !visited[node][i] {
            visited[node][i] = true
            *res = append(*res, node2)
            if dfs(node2, m, visited, res, count) {
                return true
            }
            *res = (*res)[0:len(*res)-1]
            visited[node][i] = false
        }
    }
    return false
}

func findItinerary(tickets [][]string) []string {
    m := map[string][]string{}
    visited := map[string][]bool{}
    for _, ticket := range tickets{
        from, to := ticket[0], ticket[1]
        m[from] = append(m[from], to)
    }
    for key, _ := range m {
        sort.Slice(m[key], func(i, j int) bool {
            return m[key][i]<m[key][j]
        })
        visited[key] = make([]bool, len(m[key]))
    }
    res := []string{"JFK"}
    dfs("JFK", m, visited, &res, len(tickets)+1)
    return res
}
linkedin
github
slack

Post Views: 0
Posted in MediumTagged #backtracking, #dfs, #graph

Post navigation

LeetCode: Number of Dice Rolls With Target Sum
Prepare For Code Test

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.