DSA interview question
A text-analysis contest defines the beauty of a string as the difference between the frequencies of its most common and least common characters (counting only characters that appear): "aabcb" has frequencies a:2, b:2, c:1, so its beauty is 1. The task is the total beauty over every substring. There are O(n²) substrings, and recounting each one from scratch is O(n³). Fixing the start and extending the end one character at a time lets the frequency table update in O(1), with a quick scan of 26 counters for the max and min.
Example: "aabcb" → 5.
long long beautySum(const string& s); // lowercase letters
Input s | Output | Explanation |
|---|---|---|
"aabcb" | 5 | "aab", "aabc", "aabcb", "abcb", "bcb" each have beauty 1 |
"aabcbaa" | 17 | |
"a" | 0 | A single character has beauty 0 |
"abc" | 0 | Every substring has all frequencies equal |
"aab" | 1 | Only "aab" (2 − 1) |
(Confirm: the minimum is taken over characters that appear in the substring; lowercase letters only.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in