LeetCode Entry
2097. Valid Arrangement of Pairs
Walk all edges without lifting a finger
2097. Valid Arrangement of Pairs hard substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1564
Problem TLDR
Walk all edges without lifting a finger
Intuition
Hierholzer’s algo to remember:
- DFS and remove nodes as soon as you visit them
- in post order backtrack add nodes to the result - this is the reversed walk path
Approach
- don’t spend too much time inventing algorithm with a name on it
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
fun validArrangement(p: Array<IntArray>) = buildList {
val g = p.groupByTo(hashMapOf(), { it[0] }) { it[1] }; val d = p.groupBy { it[1] }
val s = arrayListOf(g.keys.find { g[it]!!.size > (d[it]?.size ?: 0) } ?: p[0][0])
while (s.any()) g[s.last()]?.removeLastOrNull()?.let(s::add) ?: add(s.removeLast())
}.reversed().windowed(2)
pub fn valid_arrangement(p: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut g = p.iter().into_group_map_by(|e| e[0]);
let d = p.iter().counts_by(|e| e[1]);
let mut s = vec![*g.keys().find(|&k| d.get(k) < Some(&g[k].len())).unwrap_or(&p[0][0])];
from_fn(|| { while let Some(v) = g.entry(*s.last()?).or_default().pop() { s.push(v[1]) } s.pop() })
.collect_vec().windows(2).rev().map(|w| vec![w[1], w[0]]).collect()
}
Comments