HackerRank test case failed. Dijkstra Shortest Reach 2

I got stuck on test case 7, which is the only one that failed. I tried multiple times to change the code and even sought assistance from chatgpt, but I still received the same issue.

Input format: The first line contains , the number of test cases.

Each test case is as follows:

The first line contains two space-separated integers and , the number of nodes and edges in the graph.

Each of the next lines contains three space-separated integers , , and , the beginning and ending nodes of an edge, and the length of the edge.

The last line of each test case has an integer , denoting the starting position.

Question (HackerRank link)- https://www.hackerrank.com/challenges/dijkstrashortreach/problem?isFullScreen=true

Here is the test case:

Input – https://hr-testcases-us-east-1.s3.amazonaws.com/5595/input07.txt?response-content-type=text%2Fplain&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAR6O7GJNX5DNFO3PV%2F20240601%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240601T160419Z&X-Amz-Expires=7200&X-Amz-SignedHeaders=host&X-Amz-Signature=617536d9e335cdbbcda7a949a7bdf98b01f19cf4e7489ce596f75fcfbb5e614d

Expected output- https://hr-testcases-us-east-1.s3.amazonaws.com/5595/output07.txt?response-content-type=text%2Fplain&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAR6O7GJNX5DNFO3PV%2F20240601%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240601T160540Z&X-Amz-Expires=7200&X-Amz-SignedHeaders=host&X-Amz-Signature=4fc6f6018cf2f07b2a6e7415baab4605a078cad339ee5c7936a5b8a90a3fb88e

Here is the complete java 8 code i have tried (which passed all the test cases except test case 7)-

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import java.io.*;
import java.util.*;
import java.util.stream.*;
class Result {
public static class Pair implements Comparable<Pair> {
int node;
int dist;
public Pair(int node, int dist) {
this.node = node;
this.dist = dist;
}
@Override
public int compareTo(Pair other) {
return Integer.compare(this.dist, other.dist);
}
}
public static List<Integer> shortestReach(int n, List<List<Integer>> edges, int s) {
List<List<Pair>> adjList = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (List<Integer> edge : edges) {
int src = edge.get(0) - 1;
int dest = edge.get(1) - 1;
int weight = edge.get(2);
adjList.get(src).add(new Pair(dest, weight));
adjList.get(dest).add(new Pair(src, weight));
}
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[s - 1] = 0;
PriorityQueue<Pair> pq = new PriorityQueue<>();
pq.add(new Pair(s - 1, 0));
while (!pq.isEmpty()) {
Pair curr = pq.poll();
int u = curr.node;
if (curr.dist > dist[u]) {
continue;
}
for (Pair neighbor : adjList.get(u)) {
int v = neighbor.node;
int weight = neighbor.dist;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.add(new Pair(v, dist[v]));
}
}
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (i == s - 1) continue;
result.add(dist[i] == Integer.MAX_VALUE ? -1 : dist[i]);
}
return result;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = Integer.parseInt(bufferedReader.readLine().trim());
for (int tItr = 0; tItr < t; tItr++) {
String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\s+$", "").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int m = Integer.parseInt(firstMultipleInput[1]);
List<List<Integer>> edges = new ArrayList<>();
for (int i = 0; i < m; i++) {
edges.add(
Stream.of(bufferedReader.readLine().replaceAll("\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList())
);
}
int s = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> result = Result.shortestReach(n, edges, s);
bufferedWriter.write(result.stream().map(Object::toString).collect(Collectors.joining(" "))+ "n");
}
bufferedReader.close();
bufferedWriter.close();
}
}
</code>
<code>import java.io.*; import java.util.*; import java.util.stream.*; class Result { public static class Pair implements Comparable<Pair> { int node; int dist; public Pair(int node, int dist) { this.node = node; this.dist = dist; } @Override public int compareTo(Pair other) { return Integer.compare(this.dist, other.dist); } } public static List<Integer> shortestReach(int n, List<List<Integer>> edges, int s) { List<List<Pair>> adjList = new ArrayList<>(n); for (int i = 0; i < n; i++) { adjList.add(new ArrayList<>()); } for (List<Integer> edge : edges) { int src = edge.get(0) - 1; int dest = edge.get(1) - 1; int weight = edge.get(2); adjList.get(src).add(new Pair(dest, weight)); adjList.get(dest).add(new Pair(src, weight)); } int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[s - 1] = 0; PriorityQueue<Pair> pq = new PriorityQueue<>(); pq.add(new Pair(s - 1, 0)); while (!pq.isEmpty()) { Pair curr = pq.poll(); int u = curr.node; if (curr.dist > dist[u]) { continue; } for (Pair neighbor : adjList.get(u)) { int v = neighbor.node; int weight = neighbor.dist; if (dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; pq.add(new Pair(v, dist[v])); } } } List<Integer> result = new ArrayList<>(); for (int i = 0; i < n; i++) { if (i == s - 1) continue; result.add(dist[i] == Integer.MAX_VALUE ? -1 : dist[i]); } return result; } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int t = Integer.parseInt(bufferedReader.readLine().trim()); for (int tItr = 0; tItr < t; tItr++) { String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\s+$", "").split(" "); int n = Integer.parseInt(firstMultipleInput[0]); int m = Integer.parseInt(firstMultipleInput[1]); List<List<Integer>> edges = new ArrayList<>(); for (int i = 0; i < m; i++) { edges.add( Stream.of(bufferedReader.readLine().replaceAll("\s+$", "").split(" ")) .map(Integer::parseInt) .collect(Collectors.toList()) ); } int s = Integer.parseInt(bufferedReader.readLine().trim()); List<Integer> result = Result.shortestReach(n, edges, s); bufferedWriter.write(result.stream().map(Object::toString).collect(Collectors.joining(" "))+ "n"); } bufferedReader.close(); bufferedWriter.close(); } } </code>
import java.io.*;
import java.util.*; 
import java.util.stream.*;

class Result {

    public static class Pair implements Comparable<Pair> {
        int node;
        int dist;
    
        public Pair(int node, int dist) {
            this.node = node;
            this.dist = dist;
        }
    
        @Override
        public int compareTo(Pair other) {
            return Integer.compare(this.dist, other.dist);
        }
    }

    public static List<Integer> shortestReach(int n, List<List<Integer>> edges, int s) {
        List<List<Pair>> adjList = new ArrayList<>(n);
        for (int i = 0; i < n; i++) {
            adjList.add(new ArrayList<>());
        }
    
        for (List<Integer> edge : edges) {
            int src = edge.get(0) - 1;
            int dest = edge.get(1) - 1;
            int weight = edge.get(2);
            adjList.get(src).add(new Pair(dest, weight));
            adjList.get(dest).add(new Pair(src, weight));
        }
    
        int[] dist = new int[n];
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[s - 1] = 0;
    
        PriorityQueue<Pair> pq = new PriorityQueue<>();
        pq.add(new Pair(s - 1, 0));
    
        while (!pq.isEmpty()) {
            Pair curr = pq.poll();
            int u = curr.node;
    
            if (curr.dist > dist[u]) {
                continue;
            }
    
            for (Pair neighbor : adjList.get(u)) {
                int v = neighbor.node;
                int weight = neighbor.dist;
    
                if (dist[u] + weight < dist[v]) {
                    dist[v] = dist[u] + weight;
                    pq.add(new Pair(v, dist[v]));
                }
            }
        }
    
        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (i == s - 1) continue; 
            result.add(dist[i] == Integer.MAX_VALUE ? -1 : dist[i]);
        }
    
        return result;
    }

}

public class Solution {

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new    FileWriter(System.getenv("OUTPUT_PATH")));

        int t = Integer.parseInt(bufferedReader.readLine().trim());

        for (int tItr = 0; tItr < t; tItr++) {
            String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\s+$", "").split(" ");

            int n = Integer.parseInt(firstMultipleInput[0]);
            int m = Integer.parseInt(firstMultipleInput[1]);

            List<List<Integer>> edges = new ArrayList<>();

            for (int i = 0; i < m; i++) {
                edges.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\s+$", "").split(" "))
                        .map(Integer::parseInt)
                        .collect(Collectors.toList())
                );
            }

            int s = Integer.parseInt(bufferedReader.readLine().trim());

            List<Integer> result = Result.shortestReach(n, edges, s);

            bufferedWriter.write(result.stream().map(Object::toString).collect(Collectors.joining(" "))+ "n");
        }

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Here is the error: Time limit exceeded Your code did not execute within the time limits. Please optimize your code. For more information on execution time limits, refer to the environment page.

The environment page doesn’t exist.

New contributor

Puja Guchhait is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật