how to promise its the longest sequence?

  • 0
    public List<String> findItinerary(String[][] tickets) {
            List<String> result = new ArrayList();
            Map<String, ArrayList<String>> graph = new HashMap();
            for(int i=0; i<tickets.length; i++){
                    ArrayList<String> adj = new ArrayList();
                    graph.put(tickets[i][0], adj);
            for(ArrayList<String> a : graph.values()){
            backtracing(result, "JFK", graph);
            return result;
        public void backtracing(List<String> result, String current, Map<String, ArrayList<String>> graph){
            while(graph.containsKey(current) && !graph.get(current).isEmpty()){
                String s = graph.get(current).remove(0);
                backtracing(result, s, graph);
            result.add(0,current); // the most important line 

    This piece of code could pass all the test. I am just wondering how could it promise that its the longest sequence?
    if I move the code result.add(current); // the most important line inside the while loop, it will not pass the test, why?

Log in to reply

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