Why is this Greedy Appraoch correct?

In this LC problem: https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/,
in one of the steps we need to find the minimum number of adjacent swaps needed to change a string of numbers into another.

In all of the solutions I went through, a greedy appraoch was being used. This is the approach:
NOTE: I took this explanation from the discussion post written by user: @mani2017 [link to the post: link]

image

How can we argue about the correctness of this greedy appraoch? Adjacent swaps is something that comes up very often in the coding problems, so it'd be good to know about it.

Thanks!

Comments (0)