CSES problem Substring Order II

I want help with the optimization of my solution. I have tried to solved it using suffix array but I am only able to solve it for small n.

Problem linkhttps://cses.fi/problemset/task/2109.
My solution

How can I optimize my solution?

Thanks.