Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
There is an undirected weighted graph with n vertices labeled from 0 to n - 1.
You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi.
A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.
The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator.
You are also given a 2D array query, where query[i] = [si, ti]. For each query, you need to find the minimum cost of the walk starting at vertex si and ending at vertex ti. If there exists no such walk, the answer is -1.
Return the array answer, where answer[i] denotes the minimum cost of a walk for query i.
Example 1:
Input: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]
Output: [1,-1]
Explanation:
To achieve the cost of 1 in the first query, we need to move on the following edges: 0->1 (weight 7), 1->2 (weight 1), 2->1 (weight 1), 1->3 (weight 7).
In the second query, there is no walk between nodes 3 and 4, so the answer is -1.
Example 2:
Input: n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]
Output: [0]
Explanation:
To achieve the cost of 0 in the first query, we need to move on the following edges: 1->2 (weight 1), 2->1 (weight 6), 1->2 (weight 1).
Constraints:
2 <= n <= 1050 <= edges.length <= 105edges[i].length == 30 <= ui, vi <= n - 1ui != vi0 <= wi <= 1051 <= query.length <= 105query[i].length == 20 <= si, ti <= n - 1si != tiProblem summary: There is an undirected weighted graph with n vertices labeled from 0 to n - 1. You are given the integer n and an array edges, where edges[i] = [ui, vi, wi] indicates that there is an edge between vertices ui and vi with a weight of wi. A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once. The cost of a walk starting at node u and ending at node v is defined as the bitwise AND of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk, then the cost is calculated as w0 & w1 & w2 & ... & wk, where & denotes the bitwise AND operator. You are also given a 2D array query, where
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Bit Manipulation · Union-Find
5 [[0,1,7],[1,3,7],[1,2,1]] [[0,3],[3,4]]
3 [[0,2,7],[0,1,15],[1,2,6],[1,2,1]] [[1,2]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3108: Minimum Cost Walk in Weighted Graph
class UnionFind {
private final int[] p;
private final int[] size;
public UnionFind(int n) {
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
public boolean union(int a, int b) {
int pa = find(a), pb = find(b);
if (pa == pb) {
return false;
}
if (size[pa] > size[pb]) {
p[pb] = pa;
size[pa] += size[pb];
} else {
p[pa] = pb;
size[pb] += size[pa];
}
return true;
}
public int size(int x) {
return size[find(x)];
}
}
class Solution {
private UnionFind uf;
private int[] g;
public int[] minimumCost(int n, int[][] edges, int[][] query) {
uf = new UnionFind(n);
for (var e : edges) {
uf.union(e[0], e[1]);
}
g = new int[n];
Arrays.fill(g, -1);
for (var e : edges) {
int root = uf.find(e[0]);
g[root] &= e[2];
}
int m = query.length;
int[] ans = new int[m];
for (int i = 0; i < m; ++i) {
int s = query[i][0], t = query[i][1];
ans[i] = f(s, t);
}
return ans;
}
private int f(int u, int v) {
if (u == v) {
return 0;
}
int a = uf.find(u), b = uf.find(v);
return a == b ? g[a] : -1;
}
}
// Accepted solution for LeetCode #3108: Minimum Cost Walk in Weighted Graph
type unionFind struct {
p, size []int
}
func newUnionFind(n int) *unionFind {
p := make([]int, n)
size := make([]int, n)
for i := range p {
p[i] = i
size[i] = 1
}
return &unionFind{p, size}
}
func (uf *unionFind) find(x int) int {
if uf.p[x] != x {
uf.p[x] = uf.find(uf.p[x])
}
return uf.p[x]
}
func (uf *unionFind) union(a, b int) bool {
pa, pb := uf.find(a), uf.find(b)
if pa == pb {
return false
}
if uf.size[pa] > uf.size[pb] {
uf.p[pb] = pa
uf.size[pa] += uf.size[pb]
} else {
uf.p[pa] = pb
uf.size[pb] += uf.size[pa]
}
return true
}
func (uf *unionFind) getSize(x int) int {
return uf.size[uf.find(x)]
}
func minimumCost(n int, edges [][]int, query [][]int) (ans []int) {
uf := newUnionFind(n)
g := make([]int, n)
for i := range g {
g[i] = -1
}
for _, e := range edges {
uf.union(e[0], e[1])
}
for _, e := range edges {
root := uf.find(e[0])
g[root] &= e[2]
}
f := func(u, v int) int {
if u == v {
return 0
}
a, b := uf.find(u), uf.find(v)
if a == b {
return g[a]
}
return -1
}
for _, q := range query {
ans = append(ans, f(q[0], q[1]))
}
return
}
# Accepted solution for LeetCode #3108: Minimum Cost Walk in Weighted Graph
class UnionFind:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a), self.find(b)
if pa == pb:
return False
if self.size[pa] > self.size[pb]:
self.p[pb] = pa
self.size[pa] += self.size[pb]
else:
self.p[pa] = pb
self.size[pb] += self.size[pa]
return True
class Solution:
def minimumCost(
self, n: int, edges: List[List[int]], query: List[List[int]]
) -> List[int]:
g = [-1] * n
uf = UnionFind(n)
for u, v, _ in edges:
uf.union(u, v)
for u, _, w in edges:
root = uf.find(u)
g[root] &= w
def f(u: int, v: int) -> int:
if u == v:
return 0
a, b = uf.find(u), uf.find(v)
return g[a] if a == b else -1
return [f(s, t) for s, t in query]
// Accepted solution for LeetCode #3108: Minimum Cost Walk in Weighted Graph
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3108: Minimum Cost Walk in Weighted Graph
// class UnionFind {
// private final int[] p;
// private final int[] size;
//
// public UnionFind(int n) {
// p = new int[n];
// size = new int[n];
// for (int i = 0; i < n; ++i) {
// p[i] = i;
// size[i] = 1;
// }
// }
//
// public int find(int x) {
// if (p[x] != x) {
// p[x] = find(p[x]);
// }
// return p[x];
// }
//
// public boolean union(int a, int b) {
// int pa = find(a), pb = find(b);
// if (pa == pb) {
// return false;
// }
// if (size[pa] > size[pb]) {
// p[pb] = pa;
// size[pa] += size[pb];
// } else {
// p[pa] = pb;
// size[pb] += size[pa];
// }
// return true;
// }
//
// public int size(int x) {
// return size[find(x)];
// }
// }
//
// class Solution {
// private UnionFind uf;
// private int[] g;
//
// public int[] minimumCost(int n, int[][] edges, int[][] query) {
// uf = new UnionFind(n);
// for (var e : edges) {
// uf.union(e[0], e[1]);
// }
// g = new int[n];
// Arrays.fill(g, -1);
// for (var e : edges) {
// int root = uf.find(e[0]);
// g[root] &= e[2];
// }
// int m = query.length;
// int[] ans = new int[m];
// for (int i = 0; i < m; ++i) {
// int s = query[i][0], t = query[i][1];
// ans[i] = f(s, t);
// }
// return ans;
// }
//
// private int f(int u, int v) {
// if (u == v) {
// return 0;
// }
// int a = uf.find(u), b = uf.find(v);
// return a == b ? g[a] : -1;
// }
// }
// Accepted solution for LeetCode #3108: Minimum Cost Walk in Weighted Graph
class UnionFind {
p: number[];
size: number[];
constructor(n: number) {
this.p = Array(n)
.fill(0)
.map((_, i) => i);
this.size = Array(n).fill(1);
}
find(x: number): number {
if (this.p[x] !== x) {
this.p[x] = this.find(this.p[x]);
}
return this.p[x];
}
union(a: number, b: number): boolean {
const [pa, pb] = [this.find(a), this.find(b)];
if (pa === pb) {
return false;
}
if (this.size[pa] > this.size[pb]) {
this.p[pb] = pa;
this.size[pa] += this.size[pb];
} else {
this.p[pa] = pb;
this.size[pb] += this.size[pa];
}
return true;
}
getSize(x: number): number {
return this.size[this.find(x)];
}
}
function minimumCost(n: number, edges: number[][], query: number[][]): number[] {
const uf = new UnionFind(n);
const g: number[] = Array(n).fill(-1);
for (const [u, v, _] of edges) {
uf.union(u, v);
}
for (const [u, _, w] of edges) {
const root = uf.find(u);
g[root] &= w;
}
const f = (u: number, v: number): number => {
if (u === v) {
return 0;
}
const [a, b] = [uf.find(u), uf.find(v)];
return a === b ? g[a] : -1;
};
return query.map(([u, v]) => f(u, v));
}
Use this to step through a reusable interview workflow for this problem.
Sort the array in O(n log n), then scan for the missing or unique element by comparing adjacent pairs. Sorting requires O(n) auxiliary space (or O(1) with in-place sort but O(n log n) time remains). The sort step dominates.
Bitwise operations (AND, OR, XOR, shifts) are O(1) per operation on fixed-width integers. A single pass through the input with bit operations gives O(n) time. The key insight: XOR of a number with itself is 0, which eliminates duplicates without extra space.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.