← Morgan Stanley questions

Optimize double loop character comparison sum

Filed under Morgan Stanley

Given a string s, optimize the computation of the sum of abs(i - j) for all pairs (i, j) where s[i] != s[j], reducing the time complexity from O(N^2) to O(N log N) or O(N).

You've read your 3 free write-ups

Sign up free to keep reading. Your account opens the first 10 questions of every company.

Related Morgan Stanley questions

Collected from public candidate posts and coding forums. Updated Nov 2026.