This is a verified interview question from Uidai. Candidates reporting seeing this problem in recent Online Assessments (OAs) and onsite rounds. Mastering "Shortest Path with Conditional Edge Weights" covers key patterns like Graphs.
"Given an undirected graph where all edges initially have weight 1, you need to find the shortest path from a source node to all other nodes. However, there's a special constraint: any edge that connects to a designated 'special node' V has its weight reduced to 0 instead of 1. ### Function Description: You need to implement the function `solution` that takes a graph and a source node and returns the shortest distances from the source node to all other nodes, considering the given constraints. ### Parameters: - N: Number of nodes in the graph (nodes are numbered 1 to N) - M: Number of edges in the graph - edges: A 2D array where each edges[i] contains [u, v] representing an undirected edge between nodes u and v - V: The special node that triggers weight reduction (any edge touching this node has weight 0) - source: The starting node for shortest path calculation ### Return: An array of size N where result[i] represents the shortest distance from the source node to node (i+1). If a node is unreachable, return -1 for that position. ### Input Format: - The first line contains a single integer N, the number of nodes in the graph. - The second line contains a single integer M, the number of edges. - The next M lines each contain two space-separated integers u and v, representing an edge between nodes u and v (1-indexed). All edges have an initial weight of 1. The graph is undirected. - The next line contains a single integer V, representing the special node through which connected edges have their weight reduced to 0. - The last line contains a single integer source, the source node. ### Output Format: Return a single line containing a space-separated list of integers, where each integer at index i represents the shortest distance from the source node to node i+1 (1-indexed). If a node is unreachable, return -1 for that node."
Join thousands of developers practicing for Uidai.