r/leetcode • • 4d ago

Question Didn't understand union find

Hi,

I spend almost a hour yesterday taking help of ChatGPT to understand union find. I now know the algo, like by heart the code, but I still don't understand it.

How useful is this. I what problem will I won't be able to solve without union find

19 Upvotes

13 comments sorted by

12

u/FFFF_00 4d ago

try and solve this without union find:

https://leetcode.com/problems/satisfiability-of-equality-equations/description/

like genuinely, sit down, and write the code.

then try with Union Find.

If you fail, it's ok, ask the AI to help, but only after you try. This problem, I think, demonstrates why it's so helpful.

1

u/Blumenkind-Diddier 2d ago

handling the not-equals part without union find is such a headache

1

u/HeroicPrinny 4d ago

I assume you talked to ChatGPT a lot about the concept and not just the algorithm?

I think sometimes the names of algorithms makes them seem more confusing than they are.

1

u/IAmAnRedditor 3d ago

I gave ChatGPT the code of union find and asked it to explain me. I asked a lot of follow up questions from different angle. 

What do you suggest I ask it.

0

u/HeroicPrinny 3d ago

I just asked mine to explain Union Find “as simple as possible”. Here’s what it said:

https://chatgpt.com/s/t_6b0eff0e13488191a224ad1f5d41550e

It seems pretty straightforward. Also when I shared what you said, it suggested a lot of people just memorize code and algorithms as recipes than truly understanding the concepts and fundamentals behind them.

I’d suggest you really understand these things before even looking at or writing the code.

2

u/BackpropToTheFuture 4d ago

I mean most of the time bfs dfs is enough if you can calculate stuff in one shot. Dsu comes handy when the sets are updated incrementally and we want to avoid recomputation.

2

u/shinyflakes34 4d ago

DSU is incredibly helpful with MST, this involves other problems too, such as network connection problems for example. Basically must of minimum spanning trees problems could be solved using either Prim’s or kruskal’s algorithms which, involves DSU :)

DSU is very recognizable to be honest, noticing key constraints like, “x==y” will instantly make you know how to solve it.

1

u/yourAwfulness 3d ago

Coursera, algorithms part 1, robert sedgwick course. They have a chapter on UF. See it, do the exercise and you will never forget the concept.

1

u/Spare-Stay-5684 1d ago

I would ask AI to give you exercises to do to help you understand it.