Can someone help me fully grasp idea and time/space complexity with this code?
You are completely correct in your analysis.
Space.  You construct an array $x$ which has length the same as that of $b$, which is $n$.  It contains a pair for each element in $b$, so it has size $O(n)$.  The other variables do not count, hence space complexity is indeed $O(n)$.
Time.  You correctly observed that the sorting of $x$ takes time $O(n \log n)$, and that both iterations take time $O(n)$.  Everything else is arithmetic operations, which all run in $O(1)$ time.  Hence, something like $O(n) + O(n \log n) + O(n) + O(1)$, which all in all results in a time complexity of $O(n \log n)$.
Well done!